在mysql问题中选择字段

时间:2011-08-28 10:47:45

标签: php mysql sql

我无法使用SQL和PHP从表中选择字段。

我有一个名为invitations的表,其中包含以下字段:

  • senderid
  • receiverid1
  • receiverid2
  • ...
  • receiverid10

我有不同的行senderid,并希望选择与其对应的receiverid

某些receiversid可能为null,因此我只过滤非空值。

这是我的代码:

$d1 = mysql_connect($dbhost,$dbuser ,$dbpass);
mysql_select_db($dbname, $d1);

/* fetching receivers */
$q1 = mysql_query("select receiverid1,receiverid2,receiverid3,receiverid4,
        receiverid5,receiverid6,receiverid7,receiverid8,receiverid9,receiverid10  
        from invitations 
        where senderid = '528495538' ", $d1);

while($row = mysql_fetch_array($q1))
{ 
    $totalreceivers = count(array_filter($row));
    $receivers[] = array_filter($row);

}
echo '<br>';    
echo "the receivers";
echo '<br>';
print_r($receivers);
echo '<br>';
echo $totalreceivers;

使用上面的发件人ID,在表上我有2行,但是当我执行代码时,我只得到一行:

接收者Array ( [0] => 1743650643 [receiverid1] => 1743650643 ) 2

任何形式的帮助将不胜感激,谢谢。

3 个答案:

答案 0 :(得分:2)

$recievers放入数组,将$totalreceivers放入从0开始的int,并在循环之前声明它们。您在每个循环上重新分配它们而不是添加它们:

$totalreceivers = 0;
$receivers = array();
while($row = mysql_fetch_assoc($q1)) {
  $filtered = array_filter($row);
  $totalreceivers += count($filtered);
  $receivers[] = $filtered;
}

请注意,调用array_filter()一次并将其分配给变量比为每个操作调用两次更有效。此外,特别是对于上述操作,请使用mysql_fetch_assoc()代替mysql_fetch_array()

编辑看看这是否更像您想要的(略微修复)......

$receivers = array();
while($row = mysql_fetch_assoc($q1)) {
  foreach (array_filter($row) as $item) {
    $receivers[] = $item;
  }
}
$totalreceivers = count($receivers);

答案 1 :(得分:0)

将其更新为:

while($row = mysql_fetch_array($q1))
{ 
$totalreceivers += count(array_filter($row));
$receivers[] = array_filter($row);

}
echo '<br>';    
echo "the receivers";
echo '<br>';
print_r($receivers);

答案 2 :(得分:0)

你的表定义显然是错误的。

您应该将receiverid移到单独的表中