开发者

select fields in mysql problem

开发者 https://www.devze.com 2023-04-01 10:35 出处:网络
I got stuck on selecting fields from a table using SQL and PHP. I have a table named invitations with those fields:

I got stuck on selecting fields from a table using SQL and PHP.

I have a table named invitations with those fields:

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

I have different rows with the same senderid and want to select the receiverid corresponding to it.

Some receiversid may be null so I filter only non null value.

Here is my code:

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

/* fetching receivers */
$q1 = mysql_query("select receiverid1,receiverid2,receiverid3,rece开发者_如何学编程iverid4,
        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;

With the above sender id, on the table I have 2 rows but when I execute the code I get only one:

the receivers Array ( [0] => 1743650643 [receiverid1] => 1743650643 ) 2

Any kind of help will be appreciated, thank you.


Make $recievers into an array, and $totalreceivers into an int starting at 0, and declare them before the loop. You are reassigning them on each loop instead of adding to them:

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

Note that it is more efficient to call array_filter() once and assign it to a variable than it is to call it twice for each operation. Also, especially for the operation above, use mysql_fetch_assoc() instead of mysql_fetch_array().

EDIT See if this is more like what you want (slightly fixed)...

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


update it like:

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);


Your table definition is obviously wrong.

You should move receiverids into separate table

0

精彩评论

暂无评论...
验证码 换一张
取 消