如何在while循环php中使用复选框插入数据

提安:

我想将复选框的值添加到数据库中的特定行。它将值每次添加到错误的行。我尝试添加具有不同值的隐藏输入。

 if (isset($_POST['save_task'])) {
                $count=count($_POST["pro_id"]);
                
                    $query = "INSERT INTO client_program_task_activities (task_id, activity_type, type_id, show_status)
                      VALUES(?,?,?,?)";
                    $stmt = mysqli_prepare($db, $query);
                   
                    mysqli_stmt_bind_param($stmt, 'ssss', $_POST['task_id'][$i], $_POST['type'][$i], $_POST['pro_id'][$i],  $_POST['show_status'][$i]);
                    for($i=0;$i<$count;$i++){
                    mysqli_stmt_execute($stmt);
                }
                 }

$sql = "SELECT * FROM tasks  WHERE user_id='$user_id' ORDER BY date_added DESC ";
                                $result = mysqli_query($db, $sql);
                                $resultCheck = mysqli_num_rows($result);
                                if ($resultCheck > 0) {
                                   
                                    echo ' <form action="task_day.php" method="post" > 
                                  <table >
                                    <tr>
                                      <th> ADD TASK</th>
                                      <th> TASK NAME</th>
                                      <th>KCAL</th>
                                    </tr>';
                                    
                                    while ($row = mysqli_fetch_assoc($result)) {
                                         echo '<input type="hidden" name="task_id[]" value="'; echo $task_id; echo '">';
                                        echo '<input type="hidden" name="pro_id[]" value="'.$row['pro_id']. '">';
                                        echo '<input type="hidden" name="type[]" value="test">';
                                        echo '<input name=show_status[] type="hidden" value="0">
                                                  <td><input name=show_status[] type="checkbox" value="1"></td>
                                                  <td>'.$row['task_name'].'</td>
                                                  </tr>';
                                    }
                                    echo ' </table>
                               <button name="save_task" type="submit" >Save task</button>
                   </form>';
                                    
                                }
                
                
                                ?>
Abronsius教授:

也许这可以通过在循环外创建和绑定准备好的语句来帮助您理解我的意思。

<?php
    # test that ALL fields are present before trying to
    # assign them to variables or process them further.
    if( isset( 
        $_POST['save_task'],
        $_POST['task_id'],
        $_POST['type'],
        $_POST['pro_id'],
        $_POST['show_status']
    )) {
    
        # prepare the statement ONCE - and bind placeholders to variables.
        # in `mysqli` these variables do not need to exist at this point
        # whereas in PDO they do.
        
        $sql='insert into `client_program_task_activities` ( `task_id`, `activity_type`, `type_id`, `show_status`) values ( ?, ?, ?, ? )';
        $stmt=$db->prepare( $sql );
        $stmt->bind_param( 'ssss', $tid, $type, $pid, $status );
        
        foreach( $_POST['pro_id'] as $i => $pid ){
            $tid=$_POST['task_id'][$i];
            $type=$_POST['type'][$i];
            $status=$_POST['show_status'][$i];
            
            $stmt->execute();
        }
        $stmt->close();
    }
    
    
    # query to find data for table display
    $sql = 'select `task_id`, `task_name`, `pro_id` from `tasks` where `user_id`=? order by `date_added` desc';
    $stmt=$db->prepare( $sql );
    $stmt->bind_param( 's', $user_id );
    $stmt->execute();
    $stmt->bind_result( $tid, $task, $pid );
    
    
    # prepare output for table rows
    $rows=[];
    while( $stmt->fetch() ){
        $rows[]=sprintf(
            '<tr>
                <td>
                    <input type="hidden" name="task_id[]" value="%s" />
                    <input type="hidden" name="pro_id[]" value="%s" />
                    <input type="hidden" name="type[]" value="test" />
                    
                    <input name="show_status[]" type="hidden" value="0" />
                    <input name="show_status[]" type="checkbox" value="1" />
                </td>
                <td>%s</td>
                <td>### ENERGY ###</td>
            </tr>',
            
            $tid,
            $pid,
            $task
        );
    }
    $stmt->free_result();
    $stmt->close();
    
    
    
    
    
    # print the formatted table
    printf('
        <form action="task_day.php" method="post"> 
            <table>
                <tr>
                    <th>ADD TASK</th>
                    <th>TASK NAME</th>
                    <th>KCAL</th>
                </tr>
                %s
            </table>
            <button name="save_task" type="submit" >Save task</button>
        </form>',
        implode( PHP_EOL, $rows )
    );
    
?>

在不知道表模式的情况下,我无法确定以下各项是否正确,但是基于所示的表设计,这似乎可以正常工作。

<?php

    require 'db.php';

    $user_id=!empty( $_GET['user_id'] ) ? $_GET['user_id'] : false;
    
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
    </head>
    <body>
    
    
        <?php
            /*
            based upon following rudimentary table schema
            
            mysql> describe tasks;
            +------------+------------------+------+-----+-------------------+----------------+
            | Field      | Type             | Null | Key | Default           | Extra          |
            +------------+------------------+------+-----+-------------------+----------------+
            | id         | int(10) unsigned | NO   | PRI | NULL              | auto_increment |
            | task_id    | int(10) unsigned | NO   | MUL | 0                 |                |
            | task_name  | varchar(50)      | NO   |     | 0                 |                |
            | pro_id     | int(10) unsigned | NO   | MUL | 0                 |                |
            | user_id    | varchar(50)      | NO   | MUL | 0                 |                |
            | date_added | timestamp        | YES  |     | CURRENT_TIMESTAMP |                |
            +------------+------------------+------+-----+-------------------+----------------+


            mysql> describe client_program_task_activities;
            +---------------+---------------------+------+-----+---------+----------------+
            | Field         | Type                | Null | Key | Default | Extra          |
            +---------------+---------------------+------+-----+---------+----------------+
            | id            | int(10) unsigned    | NO   | PRI | NULL    | auto_increment |
            | task_id       | int(10) unsigned    | NO   |     | NULL    |                |
            | activity_type | varchar(50)         | NO   |     | NULL    |                |
            | type_id       | int(10) unsigned    | NO   |     | 0       |                |
            | show_status   | tinyint(3) unsigned | NO   |     | 0       |                |
            +---------------+---------------------+------+-----+---------+----------------+
            
            */
            
            
            # test that ALL fields are present before trying to
            # assign them to variables or process them further.
            if( isset(
                $user_id,
                $_POST['save_task'],
                $_POST['task_id'],
                $_POST['type'],
                $_POST['pro_id'],
                $_POST['show_status']
            ) && !empty( $user_id ) ) {
            
                # prepare the statement ONCE - and bind placeholders to variables.
                # in `mysqli` these variables do not need to exist at this point
                # whereas in PDO they do.
                try{
                    
                    $sql='insert into `client_program_task_activities` ( `task_id`, `activity_type`, `type_id`, `show_status`) values ( ?, ?, ?, ? )';
                    $stmt=$db->prepare( $sql );
                    $stmt->bind_param( 'ssss', $tid, $type, $pid, $status );
                    
                    foreach( $_POST['task_id'] as $key => $tid ){
                        $status = in_array( $tid, array_keys( $_POST['show_status'] ) ) ? 1 : 0;
                        $pid=$_POST['pro_id'][ $key ];
                        $type=$_POST['type'][ $key ];
                        $stmt->execute();
                    }
                    
                    $stmt->close();
                    
                }catch( mysqli_sql_exception $e ){
                    echo $e->getMessage(); # Do NOT display errors in final, production code!!!
                    #printf('<pre>%s</pre>',print_r( $_POST, true ) );
                }
            }
            
            
            
            
            
            
            # query to find data for table display
            try{
                
                $sql = 'select `task_id`, `task_name`, `pro_id` from `tasks` where `user_id`=? order by `date_added` desc';
                $stmt=$db->prepare( $sql );
                $stmt->bind_param( 's', $user_id );
                $stmt->execute();
                $stmt->bind_result( $tid, $task, $pid );
                
            }catch( mysqli_sql_exception $e ){
                echo $e->getMessage(); # Do NOT display errors in final, production code!!!
            }
            
            
            # prepare output for table rows
            /*
                Removed hidden field `show_status` and assigned
                the task ID as the index to `show_status`
            */
            $rows=[];
            while( $stmt->fetch() ){
                $rows[]=sprintf(
                    '<tr>
                        <td>
                            <input type="hidden" name="task_id[]" value="%1$d" />
                            <input type="hidden" name="pro_id[]" value="%2$d" />
                            <input type="hidden" name="type[]" value="%3$s" /><!-- using task name as value rather than "test" -->
                            <input name="show_status[%1$d]" type="checkbox" value="1" /><!-- using task ID as index -->
                        </td>
                        <td>%3$s</td>
                        <td>### ENERGY ###</td><!-- unclear what this content will be ~ assumed energy due to column name KCAL -->
                    </tr>',
                    
                    $tid,
                    $pid,
                    $task
                    
                );
            }
            $stmt->free_result();
            $stmt->close();
            
            
            
            
            
            # print the formatted table
            # action="task_day.php" 
            printf('
                <form method="post"> 
                    <table>
                        <tr>
                            <th>ADD TASK</th>
                            <th>TASK NAME</th>
                            <th>KCAL</th>
                        </tr>
                        %s
                    </table>
                    
                    <button name="save_task" type="submit">Save task</button>
                </form>',
                implode( PHP_EOL, $rows )
            );
            
        ?>
    
        
    </body>
</html>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何验证并插入register.blade.php laravel多个复选框的数据?

如何在Materialize表中使用复选框

如何在PHP发出的表格行中使用JavaScript检查所有复选框

PHP的MySQL复选框保存在while循环

如何在复选框栏杆中使用枚举

如何在React中使用复选框形式?

单击复选框后,如何在Vue.js中使用v-on传递复选框ID?

如何在PHP中使用foreach循环在多个复选框中设置所选属性?

如何在Python中使用Selenium选中复选框

如何在React钩子中使用CheckAll复选框创建复选框?

如何在Laravel中将复选框值插入数据库?

如何插入选定值的复选框数据?

如何在Android中使用单选复选框

如何在PHP中使用html复选框插入INTO

如何使用查询从数据库中获取复选框插入的数据

如何使用php在数据库的单列中插入多个复选框值

我如何在PHP中使用href传递复选框值?

如何在表格php中使用复选框

如何在css中使用复选标记作为复选框

如何在带有复选框小部件的 for 循环中使用散景悬停工具

如何使用两个插入查询从复选框中循环两个值

如何在复选框中使用 css

使用复选框php将数据插入mysql数据库

如何在带有复选框laravel的表单中使用旧值或数据库中的值

如何在reactjs中使用antd多个复选框?

如何在我的 WordPress 网站中使用复选框?

如何在UPDATE查询php中使用多个复选框

如何在反应中使用多个复选框并收集选中的复选框

如何在 jetpack compose 中使用复选框控件?