Mysql准备语句 - 选择

时间:2013-04-18 14:01:32

标签: php mysql prepare

谁可以给我一个建议?为什么查询无法为我提供预期值?感谢。

 $mysqli = new mysqli($GLOBALS["mysql_host"], $GLOBALS["mysql_user"],          $GLOBALS["mysql_passwd"], $GLOBALS["mysql_database"]);
 $stmt = $mysqli->prepare("SELECT one FROM table ORDER BY date DESC LIMIT 1");
 $last = $stmt->bind_result($one);
 $stmt->execute();
 $stmt->close();
 $mysqli->close();

 Echo $last; //it should be "abc"

2 个答案:

答案 0 :(得分:5)

我认为您必须execute,然后在fetch - 对象上调用mysql_stmt。 因为您可能会得到多个结果(行)。

使用fetch,您将推进结果光标。

文档: mysqli mysqli-stmt

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    $stmt->execute();

    /* bind variables to prepared statement */
    $stmt->bind_result($col1, $col2);

    /* fetch values */
    while ($stmt->fetch()) {
        printf("%s %s\n", $col1, $col2);
    }

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

?>

答案 1 :(得分:0)

我可以。 建议简单明了:不要使用mysqli

使用 PDO 代替

$stmt = $pdo->prepare("SELECT one FROM table ORDER BY date DESC LIMIT 1");
$stmt->execute();
$last = $stmt->fetchColumn();

echo $last; //it should be "abc"

干净,简单,有效