Inserting Data using MySQLi
When attempting to insert data using MySQLi, you may encounter a scenario where the code does not update the database despite the absence of errors during debugging. In this question, a user encountered this issue with the following code:
$stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)"); $username = /* $_POST["username"] */ "hi"; $password = /* $_POST["password"] */ "hey"; $stmt2->bind_param('s', $username); $stmt2->bind_param('s', $password); $stmt2->execute();
The issue stemmed from the incorrect use of bind_param(). Instead of binding each variable individually, it should be done all at once using the correct syntax. The corrected code is:
$stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)"); $username = /* $_POST["username"] */ "hi"; $password = /* $_POST["password"] */ "hey"; $stmt2->bind_param('ss', $username, $password); $stmt2->execute();
Additionally, using PHP 5.6 or later, the spread operator (...) can simplify the syntax even further:
$data = ['user' => 'someUser', 'password' => 'secret']; $stmt2->bind_param('ss', ...$data);
The above is the detailed content of Why Isn't My MySQLi INSERT Statement Updating the Database?. For more information, please follow other related articles on the PHP Chinese website!