亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

PHP
largeQ 2023-09-22 15:21:13
我想將復選框的值添加到數據庫中的特定行。它每次都會將值添加到錯誤的行。我嘗試添加具有不同值的隱藏輸入。 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>';
查看完整描述

1 回答

?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

也許這可以幫助您理解我通過在循環外部創建和綁定準備好的語句所暗示的含義。


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

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



查看完整回答
反對 回復 2023-09-22
  • 1 回答
  • 0 關注
  • 97 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號