无法将所有mysqli结果$ id获取到第二个查询

时间:2015-01-17 15:32:02

标签: php

我无法通过第一个查询获得所有用户ID,以便将这些ID用于第二个查询。

当我计算第一个查询时,它总是显示1。这意味着它只从sql获得一个结果。但是我想要,使用我的第一个查询,所有id都是第二个查询。

请问我的错在哪里?

我的代码:

$a = $session->username;
$b = $session->pname;
if (empty($b)) $b = $a;
$g = mysqli_query($dbh,"SELECT id FROM update WHERE `from_id`='$b' OR `to_id`='".$session->bdid."'") or die(mysqli_error($dbh));
while ($row = mysqli_fetch_assoc($g)) {
$id = $row['id'];
date_default_timezone_set('Asia/Dhaka');
$timestamp = date("M j, y; g:i a", time() - 2592000);
$count = mysqli_num_rows($g);

$u = mysqli_query($dbh,"SELECT * FROM update WHERE `id`='".$id."' AND `view` = '0' AND `created` > '".$timestamp."' ORDER BY created DESC") or die(mysqli_error($dbh));
$count1 = mysqli_num_rows($u);

$count2 = ($count - $count1);

echo ''.$count2.'';
}

2 个答案:

答案 0 :(得分:0)

mysqli_fetch_assoc一次只返回一行,这是标准行为 所以首先你应该把所有数据都放到你的数组中

$a = $session->username;
$b = $session->pname;
if (empty($b)) $b = $a;
$g = mysqli_query($dbh,"SELECT id FROM update WHERE `from_id`='$b' OR `to_id`='".$session->bdid."'") or die(mysqli_error($dbh));
$ids=[];//init ids as empty array
while ($row = mysqli_fetch_assoc($g)) {
$ids[] = $row['id'];
}

现在你需要的所有ID都在$ ids数组中,所以你可以使用它们:

$timestamp = date("M j, y; g:i a", time() - 2592000);
foreach( $ids as $id ) {
   $u = mysqli_query($dbh,"SELECT * FROM update WHERE `id`='".$id."' AND `view` = '0' AND `created` > '".$timestamp."' ORDER BY created DESC") or die(mysqli_error($dbh));
  ///some code here////
  }

<强> UPD 要在一个查询中使用所有ID,请将第二部分更改为:

$timestamp = date("M j, y; g:i a", time() - 2592000);
$u = mysqli_query($dbh,"SELECT * FROM update WHERE `id` IN( ".join(",",$ids).") AND `view` = '0' AND `created` > '".$timestamp."' ORDER BY created DESC") or die(mysqli_error($dbh));
  ///some code here////

答案 1 :(得分:0)

首先,您应该更准确地声明您的SQL语句。

$sql = "SELECT `id` FROM `update` WHERE `from_id`='".$b."' OR `to_id`='".$session->bdid."'";

此外,在while循环中,您一次只能获取一个ID,这意味着您必须定义一个数组:

while ($row = mysqli_fetch_assoc($g)) {
  $id[] = $row['id'];
}

在此之后,您可以使用您的ID数组作为第二个SQL语句,使用 IN()运算符(选中this帖子进一步阅读)。请注意,对于od Sql注入,您的代码非常容易受到攻击!

$sql2 = "SELECT * FROM `update` WHERE `id` IN (".$id.") AND `view` = '0' AND `created` > '".$timestamp."' ORDER BY `created` DESC"