mysql中的绑定参数

时间:2015-05-18 14:55:39

标签: php mysql binding parameters

我试图了解MySQL中的绑定参数。我尝试了这个测试,但是我得到了错误"在非对象上调用成员函数bind_param()"。

我做错了吗?

以下是更新后的代码:

$sql = "INSERT INTO users (field1, field2, field3) VALUES (?, ?, ?)";

connect();
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $value1, $value2, $value3);
$value1 = "test1";
$value2 = "test2";
$value3 = "test3";
$stmt->execute();

以下是connect()功能:

function connect(){
    global $conn;
    $conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
}

1 个答案:

答案 0 :(得分:2)

要在PDO中准备好的查询中绑定params,将包含params的数组传递给execute函数:

$result = $conn->prepare($sql);
$result->execute(array($value1, $value2, $value3));

<强>更新

对于mysqli版本:

connect();
$result = $conn->prepare($sql);
$result->bind_param('sss', $value1, $value2, $value3);
$result->execute();

请参阅http://php.net/manual/en/mysqli-stmt.bind-param.php