Home >Database >Mysql Tutorial >Why Does My mysqli Prepared Statement Return 'Call to a member function execute() on a non-object'?
Using mysqli Prepared Statements
When using prepared statements with mysqli, it's essential to correctly bind parameters before executing the query.
Error Debugging
The provided code encounters the error "Call to a member function execute() on a non-object" because parameter binding hasn't been performed. According to the mysqli_prepare documentation, parameter markers need to be bound using mysqli_stmt_bind_param before executing.
Complete Example with Error Handling:
The following is a more complete example that includes parameter binding, error handling, and demonstrates inserting and fetching data using prepared statements:
<?php // Establish database connection $mysqli = new mysqli("localhost", "root", "root", "test"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit; } // Prepare insert statement $stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)"); if (!$stmt) { echo "Error preparing statement: " . $mysqli->error; exit; } // Bind parameters and insert one row $name = 'One'; $age = 1; $stmt->bind_param('si', $name, $age); $stmt->execute(); if ($stmt->errno) { echo "Error executing insert: " . $stmt->error; exit; } // Insert another row with different values $name = 'Two'; $age = 2; $stmt->bind_param('si', $name, $age); $stmt->execute(); if ($stmt->errno) { echo "Error executing insert: " . $stmt->error; exit; } // Prepare select statement $stmt = $mysqli->prepare("SELECT name, age FROM users"); if (!$stmt) { echo "Error preparing statement: " . $mysqli->error; exit; } // Execute select statement and fetch results $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "{$row['name']} is {$row['age']} years old<br>"; } } // Close statement and connection $stmt->close(); $mysqli->close(); ?>
This code handles errors during statement preparation, execution, and result retrieval, providing a more robust demonstration of prepared statement usage.
The above is the detailed content of Why Does My mysqli Prepared Statement Return 'Call to a member function execute() on a non-object'?. For more information, please follow other related articles on the PHP Chinese website!