Learn how to use mysqli prepared statements for database operations
P粉838563523
2023-08-24 16:54:12
<p>I'm trying to use prepared statements, but the code below doesn't work. I received the following error: </p>
<blockquote>
<p>Fatal error: Calling non-object member function execute() on line 12 of /var/www/prepared.php</p>
</blockquote>
<pre class="brush:php;toolbar:false;"><?php
$mysqli = new mysqli("localhost", "root", "root", "test");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL:" . $mysqli->connect_error;
}
$stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)");
//Insert a row
$stmt->execute(array('one',1));
// Insert another row with different values
$stmt->execute(array('two',1));
?></pre>
<p>Also, do I need to use mysqli for prepared statements? Can anyone point me to an example of a complete prepared statement, including joins, inserts and selects, and error handling? </p>
You can also use PDO which I prefer. In fact, in your code example, you seem to be confusing PDO and Mysqli.
Unlike mysqli, you don't need to call a separate bind function, although the functionality is available if you like/want/need to use it.
Another interesting thing about PDO is named placeholders, which may be less confusing in complex queries:
From
mysqli::prepare
Documentation:bind_param
Documentation.Right now: