In an attempt to utilize prepared statements, a developer encountered challenges and received the error "Fatal error: Call to a member function execute() on a non-object." This article delves into the root cause of this issue and provides a comprehensive guide on the proper usage of prepared statements in Mysqli.
The issue arises from the omission of parameter binding before executing the prepared statement. Mysqli requires the binding of parameters to application variables via the mysqli_stmt_bind_param() function before executing the statement.
1. Parameter Binding:
$name = 'one'; $age = 1; $stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)"); // bind parameters. Refer to documentation for appropriate data types (e.g., 'si' for string and integer). $stmt->bind_param('si', $name, $age);
2. Statement Execution:
$stmt->execute();
3. Subsequent Parameter Binding and Execution:
For inserting multiple rows with different values, the parameter binding step must be repeated before each execution.
Example:
$name = 'two'; $age = 2; // Update bound parameters $stmt->bind_param('si', $name, $age); // Execute with different values $stmt->execute();
4. Complete Example:
$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 (?,?)"); try { // Insert one row $name = 'one'; $age = 1; $stmt->bind_param('si', $name, $age); $stmt->execute(); // Insert another row with different values $name = 'two'; $age = 2; $stmt->bind_param('si', $name, $age); $stmt->execute(); } catch (Exception $e) { echo "Error: " . $e->getMessage(); }
The above is the detailed content of Why Am I Getting 'Fatal error: Call to a member function execute() on a non-object' When Using Mysqli Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!