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!
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.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