简体   繁体   中英

run prepared statement in foreach loop php

I am trying to run a SQL query inside a foreach loop in php; it is not working.

This is the php file I send in ajax request. Note: Code is working without prepared statement.

<?php

require_once('..\inc\backend-func.php');
//require_once('..\inc\connection.php');

if( $_SERVER['REQUEST_METHOD']  == 'POST'){ 
    $host = 'localhost';
    $username = 'root';
    $password = '';
    $dbname = 'wcsh_database';
    $conn = new mysqli($host, $username, $password, $dbname);

    /* Check connection */
    if ($conn->connect_error) {
        die("Connection to database failed: " . $conn->connect_error);
    }
    $i = 0;
    foreach($_POST as $k ){
        $id = $_POST['id'][$i];
        $confDdate = $_POST['cdate'][$i];
        $validUntil = $_POST['valid'][$i];
        $serialNo = $_POST['serial'][$i];
        $query = $conn->prepare('INSERT INTO `conference_certification` (id,conference_date,member_validity,serialNo) values (?,?,?,?)');
        $query->bind_param('ssss',$id,$confDate,$validUntil,$serialNo);
        $query->execute();
        if ($query == false) {
            die('prepare() failed: ' . htmlspecialchars($conn->error));
        }
        $i++;
    }
}
?>

1.Please ensure the data type is file_get_contents('php://input') or $_POST; 2.if the body post data is array, iterate should be $_POST[$i]['id'] instead of $_POST['id'][$i]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM