简体   繁体   中英

PHP mysqli prepared insert statement fails

Here is the code. $fieldNamesA and $fieldValsA are created in a foreach loop from POST variables:

$fieldNamesS = implode(',',$fieldNamesA);
$fieldValsS = implode(',',$fieldValsA);
$mysqli = new mysqli('localhost', 'user', 'pw', 'db');
mysqli_report(MYSQLI_REPORT_ALL);

$stmt = $mysqli->prepare('INSERT INTO users (?) VALUES (?)');
if ($stmt === FALSE) {
    die ("Mysql Error: " . $mysqli->error);
}
$stmt->bind_param('ss', $fieldNamesS,$fieldValsS);
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

Here are error msgs:

Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?) VALUES (?)' at line 1' in userreg.php:47
Stack trace:
#0 userreg.php(47): mysqli->prepare('INSERT INTO use...')
#1 {main}
  thrown in /userreg.php on line 47

I don't understand why it is complaining that there is something wrong with my insert statement. If I hardcode the column/field names, I get an error that the number of columns does not match the number of values, which is not correct. I var_dumped the variables just to make sure and they have the same number of parameters.

I don't think you can use placeholders for the column names with PHP Mysqli.

Check out this answer which talks about a PHP class I wrote to extend the mysqli class. It will save you some time and it also does all the automatic placeholder bindings.

better_mysqli class

You need to provide the names of the fields on the left side of VALUES then you need one ? for each of the values:

INSERT INTO some_table (some, columns) VALUES (?, ?)

EDIT

You cannot have placeholders in the column list. See http://php.net/manual/en/mysqli.prepare.php

The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign...

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