Php 不从2个表循环
这段代码没有循环,我一直在用return和array测试这段代码 我怎样才能修好它?Php 不从2个表循环,php,pdo,Php,Pdo,这段代码没有循环,我一直在用return和array测试这段代码 我怎样才能修好它? 它只显示一个结果,我希望所有结果都来自数据库。您只检索一个结果: $sth = $db->prepare("SELECT * FROM users, profile_post WHERE id='$id'"); $sth->execute(); $row = $sth->fetch(PDO::FETCH_ASSOC); $stuff = array('Published b
它只显示一个结果,我希望所有结果都来自数据库。您只检索一个结果:
$sth = $db->prepare("SELECT * FROM users, profile_post WHERE id='$id'");
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$stuff = array('Published by' => $row['firstname']. " " .$row['lastname'], 'Content profile:' => $row["content"]);
foreach ($stuff as $key => $value) {
echo "$key: $value\n";
}
这是从数据库中获取任何内容(在本例中是一行)的唯一位置
您的foreach在$stuff
数组上循环,该数组是您使用$row
中的内容定义的,它只包含由发布的和内容配置文件:
键
相反,您希望迭代实际的fetch
调用:
$row = $sth->fetch(PDO::FETCH_ASSOC);
。。应该给你所有的行。但是这里还有两个问题
您的SQL查询没有联接条件,因此您是users
和profile\u post
,这意味着users
中的每一行都与profile\u post
中的每一行联接。总行数将成为用户中的行*配置文件中的行\u post
——这可能不是您想要的
通过将profile\u post.user\u id=users.id
添加到WHERE条件,可以添加连接条件
第二个问题是,您正在使用->prepare
,但在构建查询本身时仍在使用$id
。您希望使用占位符,然后在执行语句时给出值,并从外部提供值
$sth = $db->prepare("SELECT * FROM users, profile_post WHERE id='$id'");
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
// process each row as you need here
var_dump($row);
}
$sth = $db->prepare("
SELECT
*
FROM
users, profile_post
WHERE
profile_post.user_id = users.id AND
users.id = :id
");
$sth->execute([':id' => $id]);