使用 mysqli 预准备语句
在 mysqli 中使用预准备语句时,在执行查询之前正确绑定参数非常重要。
错误调试
提供的代码遇到错误“Call to a member functionexecute() on a non-object”,因为尚未执行参数绑定。根据 mysqli_prepare 文档,在执行之前需要使用 mysqli_stmt_bind_param 绑定参数标记。
带有错误处理的完整示例:
以下是一个更完整的示例,包括参数绑定、错误处理,并演示使用准备好的插入和获取数据语句:
<?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(); ?>
此代码处理语句准备、执行和结果检索期间的错误,提供更强大的预准备语句用法演示。
以上是为什么我的 mysqli 准备语句返回'调用非对象上的成员函数execute()”?的详细内容。更多信息请关注PHP中文网其他相关文章!