使用PDO和关系数据库获取行 [英] Fetch row with pdo and relational database
问题描述
我有一个小问题,我有一个包含2个表,用户和注释的数据库,我需要使用pdo打印结果. 如果我尝试这段代码,一切都会很好:
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>";
}
但是,如果我尝试添加一个获取结果的变量,我得到的结果将完全不同,只有2行,并且只有值的第一个字母...
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>";
}
推荐答案
如果我尝试这段代码,一切都会很好:
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>" ;
}
fetch()
仅获得一条记录,而fetchAll()则按照名称提示进行操作
while fetch()
is getting you only one record, fetchAll() is doing what the name suggests
这篇关于使用PDO和关系数据库获取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!