Use MySQLi Prepared Statement to Enter Dynamic, Multiple Rows into Database?

╄→гoц情女王★ 提交于 2019-12-14 04:13:07

问题


I have created a HTML form where users would submit their name, email, and language skills. Since a user may speak more than one language, user will be able to generate additional rows by clicking an "add" button.

The form will then be submitted and entered into a MySQL database. I'm using two tables to hold the received data, whereas the user-id in the first table will be auto_incremented:

| (user-id) | name | email|
| user-id | language | proficiency|

Now I'm trying to write the PHP code, which looks something like this:

$name = $_POST['name'];
$email = $_POST['email'];

$add_table1 = $mysqli->prepare("INSERT INTO table1 (name, email) VALUES (?, ?)");
$add_table2 = $mysqli->prepare("INSERT INTO table2 (user_id, language, proficiency) VALUES (?, ?, ?)");

$add_table1->bind_param("ss", $name, $email);
$add_table1->execute();
$user-id = $mysqli->insert_id;

foreach($_POST['language'] as $index => $language) {
    $index = intval($index);
    $language = mysql_real_escape_string($language);
    $proficiency = mysql_real_escape_string($_POST['proficiency'][$index]);
    $add_table2->bind_param("iss", $user-id, $language, $proficiency);
    $add_table2->execute();
}
$add_table1->close();
$add_table2->close();
$mysqli->close();

The table should look like this

| 1 | Mark | mark@me.com |
| 2 | Sue  | sue@me.net |

|1 | English | perfect |
|1 | Spanish | awesome |
|2 | English | great |
|2 | French | ok |
|2 | Korean | fluent |

However, with my code table 1 looks fine, but table 2 looks like this

| 1 |  |  |
| 2 |  |  |

Can somebody help? Thanks!


回答1:


One thing I should point out is that you don't use mysql_real_escape_string with prepared statements.

Another thing is that $user-id is not a valid variable name. You can't use a hyphen.

Edit:

It's a good thing to turn on error reporting and to output mysqli/mysqli_stmt::$error when anything fails. Most problems can be resolved with these.




回答2:


Your php mysqli code looks pretty good. Are you sure you are retreiving correctly the POST values? int the foreach loop print $language and $proficiency before executing the queries



来源:https://stackoverflow.com/questions/9940465/use-mysqli-prepared-statement-to-enter-dynamic-multiple-rows-into-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!