mysqli准备语句错误?

时间:2010-05-18 19:26:26

标签: php sql mysql

$ mysqli = new mysqli(“localhost”,“root”,“”,“test”);     $ mysqli-> query('PREPARE mid FROM“SELECT name FROM test_user WHERE id =?”');     //工作代码开始     // $ res = $ mysqli-> query('PREPARE mid FROM“SELECT name FROM test_user”');     // $ res = $ mysqli-> query('EXECUTE mid;')或die(mysqli_error($ mysqli));     //工作代码结束..     $ res = $ mysqli->查询('EXECUTE mid 1;')或死(mysqli_error($ mysqli));

while($resu = $res->fetch_object()) {
    echo '<br>' .$resu->name;
}

错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1

我的php版本是PHP Version 5.3.0和mysql

mysqlnd 5.0.5-dev - 081106 - $Revision: 1.3.2.27 $ 

我使用where clause

得到了正确的结果

2 个答案:

答案 0 :(得分:2)

将SELECT函数用于SELECT查询:

http://php.net/manual/en/mysqli.prepare.php

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    /* close statement */
    $stmt->close();
}

答案 1 :(得分:0)

http://dev.mysql.com/doc/refman/5.1/en/execute.html

您需要在EXECUTE语句中使用using子句。所以你可以这样做:

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query('PREPARE mid FROM "SELECT name FROM test_user WHERE id = ?"');
$mysqli->query('SET @var1 = 1;');
$res = $mysqli->query( 'EXECUTE mid USING @var1;') or die(mysqli_error($mysqli));