Home >Backend Development >PHP Tutorial >Why Does My MySQLi Prepared Statement Throw a 'Call to a member function execute() on a non-object' Error?

Why Does My MySQLi Prepared Statement Throw a 'Call to a member function execute() on a non-object' Error?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 18:07:15174browse

Why Does My MySQLi Prepared Statement Throw a

Understanding mysqli Prepared Statements

In using prepared statements with mysqli, it's important to adhere to specific guidelines to ensure proper functionality.

Resolving the Error

In the provided code, the error:

Fatal error: Call to a member function execute() on a non-object in ...

suggests that the prepared statement is not correctly bound to variables before execution. To resolve this:

// Bind parameters to variables
$name = 'one';
$age = 1;
$stmt->bind_param('si', $name, $age);

Using mysqli for Prepared Statements

Mysqli is a suitable choice for using prepared statements in PHP. It's an established and well-documented database interface.

Complete Example with Prepared Statements

<?php

// Establish database connection
$mysqli = new mysqli('localhost', 'root', 'root', 'test');

// Prepare statement
$stmt = $mysqli->prepare('INSERT INTO users (name, age) VALUES (?, ?)');

// Bind variables
$name = 'one';
$age = 2;
$stmt->bind_param('si', $name, $age);

// Insert data with prepared statement
$stmt->execute();

// Check for errors
if ($mysqli->error) {
    echo 'Error: ' . $mysqli->error;
} else {
    // Data inserted successfully
}

// Prepare select statement
$stmt = $mysqli->prepare('SELECT * FROM users WHERE name = ?');

// Bind variable
$name = 'one';
$stmt->bind_param('s', $name);

// Execute select query
$stmt->execute();

// Fetch results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row['id'] . ' - ' . $row['name'] . ' - ' . $row['age'] . '<br>';
}

// Close statement and connection
$stmt->close();
$mysqli->close();

?>

This comprehensive example demonstrates the entire process from establishing a connection to inserting and selecting data with prepared statements, including error handling.

The above is the detailed content of Why Does My MySQLi Prepared Statement Throw a 'Call to a member function execute() on a non-object' Error?. 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