Home >Database >Mysql Tutorial >Why Isn't My MySQLi INSERT Statement Updating the Database?

Why Isn't My MySQLi INSERT Statement Updating the Database?

Linda Hamilton
Linda HamiltonOriginal
2024-11-20 00:55:03598browse

Why Isn't My MySQLi INSERT Statement Updating the Database?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn