问题
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>";
}
回答1:
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
回答2:
Both your samples aren't functionning properly :
In the first one you loop over every row except the first row, for which you did a fetch, and then did nothing with this first row.
In the second one you loop over every field of the first row, which produce some unexepected output.
来源:https://stackoverflow.com/questions/39292919/fetch-row-with-pdo-and-relational-database