Mr.Smithyyy
Mr.Smithyyy

Reputation: 1339

PDO expecting all results to show up but only one shows

I'm trying to execute a statement where it will show all of the results for each row of my table but all it is doing is showing the results from the last row.

<?php
    require_once('php/dbconfig.php');

    $stmt = $DB_con->prepare("SELECT * FROM users");
    $stmt->execute();

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        $name = array($row['user_name']);
        $email = array($row['user_email']);
    }
    echo $name[0];
?>

This will work but it will only echo out the name of the last person in my table. If I try to replace the 0 with any other number nothing will show.

I would like to be able to show all users and emails in a list.

Upvotes: 0

Views: 37

Answers (1)

Marshall Davis
Marshall Davis

Reputation: 3650

In the following block you are assigning each name to the variable $name.

while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $name = array($row['user_name']);
    $email = array($row['user_email']);
}

I think you intend to either echo $name each iteration of the loop by adding the echo to the loop as:

while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $name = $row['user_name'];
    $email = $row['user_email'];
    echo "{$name} - {$email}";
}

or to add it to an array of names by changing the assignment from $name to $name[] which means 'the next index of the $name array'.

Fetch also returns one record, so you'll need to loop the results or change to fetchAll as suggested by other answers.

Upvotes: 1

Related Questions