Pergunta

I have 2 rows of data in my database and I am trying to fetch all rows

$query = mysqli_query($connection, "select username, email, is_admin from adminUsers");

$results = mysqli_fetch_assoc($query);

I have tried mysqli_fetch_assoc, mysqli_fetch_row, mysqli_fetch_array all of them just return 1 row of data.

Foi útil?

Solução

mysqli_fetch_*() functions except mysqli_fetch_all(), if supported, fetch one row. Loop and fetch:

while($row = mysqli_fetch_assoc($query)) {
    print_r($row);
    //or you can echo $row['username'] etc...
    //or store in an array to loop through later
    $rows[] = $row;
}

If you use mysqlnd there is a mysqli_fetch_all() or use:

if(!function_exists('mysqli_fetch_all')) {
function mysqli_fetch_all($result, $resulttype=MYSQLI_BOTH) {
    while($row = mysqli_fetch_array($result, $resulttype)) {
        $rows[] =$row;
    }
    return $rows;
}
}

$results = mysqli_fetch_all($query);

But then you have to loop through all the returned rows anyway:

foreach($results as $row) {
    print_r($row);
    //or you can echo $row['username'] etc...
}

Outras dicas

Switch to PDO to do it in a single go... Use PDOStatement::fetchAll

<?php

//.. Do the neccessary PDO connections...
$sth = $dbh->prepare("select username, email, is_admin from adminUsers");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);

(or)

You need to loop through them... [MySQLi]

$query = mysqli_query($connection, "select username, email, is_admin from adminUsers");
$res = array();
while($results = mysqli_fetch_assoc($query))
{
 $res[] = $results;
}

print_r($res);

Use while loop for fetching all lines:

while ($result = mysqli_fetch_assoc($query))
{
    // Rest of your code. See an example below
    echo $result['username'];
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top