vendredi 26 décembre 2014

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.





Aucun commentaire:

Enregistrer un commentaire