使用预准备语句从Select * query返回结果

时间:2016-03-26 19:35:17

标签: php

我有以下测试脚本来调整所有当前程序以使用预处理语句...无法找到正确的语法/结构来读取结果行:

    $userid = "admin";
    $stmt = mysqli_stmt_init($link);
    if (mysqli_stmt_prepare($stmt, 'SELECT * FROM user_info WHERE userid = ?')) {
        mysqli_stmt_bind_param($stmt, "s", $userid);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_store_result($stmt);
        $number_of_rows = mysqli_stmt_num_rows($stmt);
        echo "Number of Rows: $number_of_rows<br />";
        $result = mysqli_stmt_get_result($stmt);
        for($i=0;$i<$number_of_rows;$i++){  
            $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
            echo $row["id"];
        }
        mysqli_stmt_close($stmt);
    }
    else{
        // Catch a database error here
        die("Could not query database.");
    }

如何正确引用结果(使用程序)?

1 个答案:

答案 0 :(得分:0)

试试这个:

$userid = "admin";
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, 'SELECT * FROM user_info WHERE userid = ?')) {
    mysqli_stmt_bind_param($stmt, "s", $userid);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_store_result($stmt);
    $number_of_rows = mysqli_stmt_num_rows($stmt);
    echo "Number of Rows: $number_of_rows<br />";
    $result = mysqli_stmt_get_result($stmt);

    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))  
        echo $row["id"];
    }

    mysqli_stmt_close($stmt);
}
else{
    // Catch a database error here
    die("Could not query database.");
}

查看获取结果函数的php手册:http://php.net/manual/en/mysqli-stmt.get-result.php(示例#2程序样式)