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
Release: 2024-11-20 00:55:03
Original
588 people have browsed it

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();
Copy after login

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();
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template