如何在PHP中使用mysqli准备的语句? [英] How to use mysqli prepared statements in PHP?

查看:66
本文介绍了如何在PHP中使用mysqli准备的语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试准备好的语句,但是下面的代码不起作用.我收到错误消息:

致命错误:在非对象中调用成员函数execute() /var/www/prepared.php,第12行

<?php

    $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 (?,?)");

    // insert one row
    $stmt->execute(array('one',1));

    // insert another row with different values
    $stmt->execute(array('two',1));
?>

此外,我是否需要对准备好的语句使用mysqli?谁能指出我有关从连接到插入再到带有错误处理的选择的准备好的语句的完整示例?

解决方案

来自 mysqli::prepare文档:

在执行语句或获取行之前,必须使用mysqli_stmt_bind_param()和/或mysqli_stmt_bind_result()将参数标记绑定到应用程序变量.

bind_param文档.

即:

$name = 'one';
$age  = 1;

$stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)");

// bind parameters. I'm guessing 'string' & 'integer', but read documentation.
$stmt->bind_param('si', $name, $age);

// *now* we can execute
$stmt->execute();

I am trying out prepared statements, but the below code is not working. I am getting the error:

Fatal error: Call to a member function execute() on a non-object in /var/www/prepared.php on line 12

<?php

    $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 (?,?)");

    // insert one row
    $stmt->execute(array('one',1));

    // insert another row with different values
    $stmt->execute(array('two',1));
?>

Also, do i need to use mysqli for prepared statements? Can anyone point me to a complete example on prepared statements from connection to insertion to selection with error handling?

解决方案

From the mysqli::prepare docs:

The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.

bind_param docs.

i.e.:

$name = 'one';
$age  = 1;

$stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)");

// bind parameters. I'm guessing 'string' & 'integer', but read documentation.
$stmt->bind_param('si', $name, $age);

// *now* we can execute
$stmt->execute();

这篇关于如何在PHP中使用mysqli准备的语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆