php mysql 查询,其中有一个循环
我正在尝试检索数据库中用户的结果,然后如果选中我的复选框以仅检索有照片的用户来显示这些结果,但我似乎不知道如何循环这些结果,或者如果我什至是在正确的背景下这样做的。 `
$photos = $_POST['pcbox'];
$basicsql = "SELECT * FROM users";
$basicsql .= "WHERE status > '1'";
if($photos=='1'){
$sql = mysql_query("SELECT user_id FROM pictures GROUP BY user_id");
while($row2 = mysql_fetch_assoc($sql))
$options[] = " AND (users.user_id = '$row2[user_id]')";
foreach($options as $key => $str){
$basicsql .= $str;
}
}
$basicsql .= " ORDER BY users.last_login DESC";
$pagesql = mysql_query($basicsql);
一切正常,直到选中该复选框
I'm trying to retrieve the results of users in my database, and then if my checkbox is selected to retrieve only users who have photos to show those results, but I can't seem to figure out how to loop through those results or if I am even doing it in the right context.
`
$photos = $_POST['pcbox'];
$basicsql = "SELECT * FROM users";
$basicsql .= "WHERE status > '1'";
if($photos=='1'){
$sql = mysql_query("SELECT user_id FROM pictures GROUP BY user_id");
while($row2 = mysql_fetch_assoc($sql))
$options[] = " AND (users.user_id = '$row2[user_id]')";
foreach($options as $key => $str){
$basicsql .= $str;
}
}
$basicsql .= " ORDER BY users.last_login DESC";
$pagesql = mysql_query($basicsql);
All works until the checkbox is selected
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能对嵌套循环使用相同的数据库句柄。您需要为每一个显式设置数据库句柄。
但是,您可以仅在一个 sql 查询中完成此操作。
观察:
Select * from users u inside join pictures p on u.id=p.user_id
其中状态> 1
INNER JOIN 只会为您提供在 pictures 表中具有行的用户。
这将为您提供只有图片的用户。
编辑
这将给出图片的数量,并且只有 1 个用户行。
从用户 u 中选择姓名、电子邮件、地址、状态、计数(*)作为 num_pics,按姓名、电子邮件、地址、状态将 u.id=p.user_id 组上的图片 p 内加入
其中状态> 1
You can't use the same db handle for nested loops. You need to explicitly set the db handle for each one.
However, you can just do it in one sql query.
Observe:
Select * from users u inner join pictures p on u.id=p.user_id
where status > 1
An INNER JOIN will give you only users that have rows in the pictures table.
This will give you users that have pictures only.
Edit
This will give the number of pitcures and only 1 user row.
Select name,email,address,status,count(*) as num_pics from users u inner join pictures p on u.id=p.user_id group by name,email,address,status
where status > 1
不太确定这是否是您正在寻找的。也未经测试。
Not exactly sure if this is what you're looking for. Untested as well.
此外,在开始循环选项之前关闭 while。
Furthermore, close while before start looping in options.