尝试从数据库打印结果时出现未定义的错误

时间:2019-01-31 08:39:56

标签: php mysql mysqli

我正在学习如何在php端进行数据库编码。我已经成功地将信息插入到数据库中,但是我很难从数据库中获取信息。如何打印数据?没什么,我想知道我们获取数据的原始方式,例如print_r。这是我的代码:

<?php

$conn = mysqli_connect($servername, $dBUsername, $dbPassword, $dbName);
$stmt = mysqli_stmt_init($conn);
$result = fetch_ids_outs($stmt, $id);

function fetch_ids_outs($stmt, $id) {

    $userID = search_for_user($stmt, $id);
    if ($userID == false) return "User not in Database";

    // Otherwise get the data
    $sql = "SELECT * FROM users WHERE user_id = ?";
    if(!mysqli_stmt_prepare($stmt, $sql)) {
        return false;
    } else {
        mysqli_stmt_bind_param($stmt, "i", $userID);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_store_result($stmt);
        while($row = $stmt->fetch_array()) {
          echo $row['name'];
          echo "<br/>";
        }
    }
}

错误:

Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetch_array() in C:\xampp\htdocs\outfit\save_outfit.test\test.php:77 Stack trace: #0 C:\xampp\htdocs\outfit\save_outfit.test\test.php(88): fetch_cids_outs(Object(mysqli_stmt), 151172293) #1 {main} thrown in C:\xampp\htdocs\outfit\save_outfit.test\test.php on line 77

1 个答案:

答案 0 :(得分:1)

我认为您的意思是get_result(),而不是store_result()

这里是例子:

function fetch_ids_outs($stmt, $id) {

    $userID = search_for_user($stmt, $id);
    if ($userID == false) return "User not in Database";

    // Otherwise get the data
    $sql = "SELECT * FROM users WHERE user_id = ?";
    if(!mysqli_stmt_prepare($stmt, $sql)) {
        return false;
    } else {
        mysqli_stmt_bind_param($stmt, "i", $userID);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt); // get result
        while($row = mysqli_fetch_assoc($result)) { // fetch by associative index
          echo $row['name'];
          echo "<br/>";
        }
    }
}