php - mysql中选择字段问题

标签 php mysql sql

我在使用 SQL 和 PHP 从表中选择字段时陷入困境。

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

  • 发件人ID
  • receiverid1
  • receiverid2
  • ...
  • receiverid10

我有不同的行具有相同的 senderid,并且想要选择与其对应的 receiverid

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

这是我的代码:

$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 行,但当我执行代码时,我只得到一行:

接收者数组 ( [0] => 1743650643 [receiverid1] => 1743650643 ) 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);

关于php - mysql中选择字段问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7220464/

相关文章:

php - 在 Symfony3 上验证文件扩展名

php - 这个php代码可以sql注入(inject)吗?

mysql - 我可以将 2 个不同的查询(返回单个记录)合并到一个返回单个记录的查询中吗?

mysql - 如果取消,我是否会删除或取消用户的喜欢/不喜欢?

javascript - 客户端和服务器端编程有什么区别?

php - yii-CGridView的列使用类显示php警告

php - 将 PHP 变量传递给 JavaScript

php - 如何将传入的电子邮件消息插入 mySQL 数据库?

python - SQLAlchemy - 带连接的复杂子查询

sql - 我需要在 T-SQL 数据透视查询中更改哪些内容才能实现此特定输出?