簡體   English   中英

如何在 while 循環 php 中使用復選框插入數據

[英]How to insert data using a checkbox inside a while loop 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>';
                                    
                                }
                
                
                                ?>

也許這可以通過在循環外創建和綁定准備好的語句來幫助您理解我的意思。

<?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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM