简体   繁体   中英

How to bind multiple parameters to MySQLi prepared statement

I have a variable number of parameters to insert and I got the error (2031) No data supplied for parameters in prepared statement after the warning Number of variables doesn't match number of parameters in prepared statement in SaveIntermediateData.php5 on line 49 .

$link = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
if( ! $link ) {
    echo "<h1>new mysqli() failed!</h1>";
    exit( 0 );
}
$queryText =
    "CREATE TABLE IF NOT EXISTS visitors (".
        "id    VARCHAR( 512) CHARACTER SET ASCII NOT NULL,".
        "name  VARCHAR(  80) CHARACTER SET ASCII NOT NULL,".
        "value VARCHAR(4096) NOT NULL,".
        "PRIMARY KEY ( `id`, `name` )".
    ")";
$link->query( $queryText );
$queryText = "INSERT INTO visitors (id,name,value) VALUES ";
foreach( $_POST as $name => $value ) {
    $queryText .= '(?,?,?),';
}
$queryText  = substr( $queryText, 0, -1 );
$queryText .= ' ON DUPLICATE KEY UPDATE name = VALUES( name ), value = VALUES( value )';
$id         = session_id();
$stmt       = $link->prepare( $queryText );
if( $stmt ) {
    $param_nr = 1;
    foreach( $_POST as $name => $value ) {
        $stmt->bind_param( 'sss', $id, $name, $value ); //<<<<<<<<< line 49
    }
    if( $stmt->execute()) {
        echo '<h1>OK</h1>';
    }
    else {
        echo "<h1>(".$stmt->errno.") ".$stmt->error."</h1>";
    }
}
else {
    echo "<h1>".$link->error."</h1>";
}
$link->close();

I believe only the last bind_param is taken in account. In Java, it's possible to use an index to bind a parameter but I don't know such a method with mysqli . I may create a full text query but I prefer use binding to avoid injection.

You can only call bind_param once , so you'll have to add all the params you want into an array, then call it via call_user_func_array .

Try this:

$params = array('');
foreach( $_POST as $name => $value ) {
    $params[0] .= 'sss';
    array_push($params, $id, $name, $value);
}

call_user_func_array(array($stmt, 'bind_param'), $params);

if( $stmt->execute()) {
    echo '<h1>OK</h1>';
}

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