pedofearbear pedofearbear - 3 months ago 15
MySQL Question

Fetch row with pdo and relational database

i have a little problem, i have a database with 2 tables, users and comments and i need to print the result with pdo.
if i try this code, everything works great:

$stmt = $dbConnection->prepare("SELECT comment_text, username FROM users, comments WHERE users.user_id = comments.user_id");
$stmt->execute();
$stmt->fetch(PDO::FETCH_ASSOC);

foreach ($stmt as $row) {
echo $row['comment_text'] . "<br>By " . $row['username'] . "<br>";
}


But if i try to add a variable which get the result of fetch i get a totally different result with only 2 rows and only the first letter of the value...

$stmt = $dbConnection->prepare("SELECT comment_text, username FROM users, comments WHERE users.user_id = comments.user_id");
$stmt->execute();
$comment = $stmt->fetch(PDO::FETCH_ASSOC);

foreach ($comment as $row) {
echo $row['comment_text'] . "<br>By " . $row['username'] . "<br>";
}

Answer

if i try this code, everything works great:

it is not.
this way you are losing the very first comment. So it should be just

$stmt->execute();
foreach($stmt as $row )
{
    echo $row['comment_text']."<br>By ".$row['username']."<br>" ;
}

in case you want to save the result in array, you have to use the appropriate function for that:

$stmt->execute();
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($comments as $row )
{
    echo $row['comment_text']."<br>By ".$row['username']."<br>" ;
} 

while fetch() is getting you only one record, fetchAll() is doing what the name suggests