首页 > 数据库 > mysql教程 > 为什么我的 mysqli 准备语句返回'调用非对象上的成员函数execute()”?

为什么我的 mysqli 准备语句返回'调用非对象上的成员函数execute()”?

DDD
发布: 2024-12-21 03:54:09
原创
551 人浏览过

Why Does My mysqli Prepared Statement Return

使用 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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板