Mikie
Mikie

Reputation: 115

Getting an undefined error when trying to print results from database

I'm learning how to do database coding on the php side. I've managed to successfully insert information into my database but I am having trouble getting from it. How can I print the data out? Nothing fancy, I would like to know the raw way we get the data out, so something like print_r. Here is my code:

<?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/>";
        }
    }
}

Error:

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

Upvotes: 2

Views: 280

Answers (1)

Kevin
Kevin

Reputation: 41885

I think you mean get_result(), not store_result().

Here's the example:

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/>";
        }
    }
}

Upvotes: 1

Related Questions