Loop results PDO PHP

前端 未结 2 401
小鲜肉
小鲜肉 2021-01-06 15:03

I\'m trying to fetch all records from my table on my site, I have the following

$sth = $conn->prepare(\"SELECT * FROM directory WHERE user_active != \'\'         


        
相关标签:
2条回答
  • 2021-01-06 15:45

    You need to use a loop:

    while ($result = $sth->fetch(PDO::FETCH_ASSOC)) {
        echo $result[First_Name];
        echo ' ' . $result[Surname];
    }
    

    Or you could use fetchAll method:

    foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $result) {
        echo $result[First_Name];
        echo ' ' . $result[Surname];
    }
    

    And Note: If First_Name and Surname are not constants, then you should use the string as the key name.

    $result['First_Name'] and $result['Surname']

    0 讨论(0)
  • 2021-01-06 16:01

    Well, you only call $sth->fetch once. You need to loop over the results.

    while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
       echo $row['First_Name'] . ' ' . $row['Surname'] . "\n";
    }
    

    Also don't call array string indexes without braces. This way PHP checks if the key is a CONSTANT, then casts it to string. This is just bad practice and might lead to unexpected bahavior.

    If this returns only one row, you probably have only one row in the database (or the result set). Show us more code!

    0 讨论(0)
提交回复
热议问题