0

I am using mysqli to query an item database. I am trying to create an array out of the items in the database, but am stuck. Here is what I have so far.

$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'test';

$connection = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

if ($query = $connection->prepare('SELECT name, due_date, complete FROM items WHERE user_id = ?')) {
    $query->bind_param('i', $_SESSION['id']);
    $query->execute(); 
    $query->store_result();
    //var_dump($query->num_rows);
    if ($query->num_rows > 0) {
        $query->bind_result($name, $due_date, $complete);
        //$query->fetch();

        while ($query->fetch()) {

       }
    }
    $query->close();

}

I am completely unsure how to turn this into an array for use in a foreach loop in my list of items.

1 Answer 1

1

If you have mysqlnd, just use ->get_result() after execute().

$query = $connection->prepare('SELECT name, due_date, complete FROM items WHERE user_id = ?');
$query->bind_param('i', $_SESSION['id']);
$query->execute();
$result = $query->get_result();
$rows = $result->fetch_all(MYSQLI_ASSOC); // fetch as associative

// then make your foreach or whatnot
foreach ($rows as $row) {
    // echo $row['name'];
}

If you don't want them all loaded up immediately, you can still use the while + fetch combo:

while ($row = $result->fetch_assoc()) {
    // echo $row['name']
    // $data[] = $row;
    // or whatever you need to do
}
Sign up to request clarification or add additional context in comments.

1 Comment

@TheDizzle sure glad this helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.