0

I am working on a system where a query checks the database for records matching multiple ids and puts each row into it's own array. So far I only got the last row to echo out in it's own array. Here is the query code:

$query = "SELECT * FROM messages WHERE senderid IN ($senderids) ORDER BY messageid DESC";
$resource = mysql_query($query, $database);
$result = mysql_fetch_array($resource);
foreach($result as $result1)
    {
    print_r($result1);
    echo '<br>';
    }

This is what echos in the browser:

2
2
1
1
TEST MSG 2
TEST MSG 2
2014_09_13_01:29:59
2014_09_13_01:29:59

This is what should echo:

Array ([messageid] => 1 [senderid] => 1 [message] => test message [date] => 2014_09_13_01:01:09)
Array ([messageid] => 2 [senderid] => 1 [message] => TEST MSG 2 [date] => 2014_09_13_01:29:59)

How would I go about fixing this issue?

2
  • just for fyi....your code is open for sql injection...search for mysqli_ or PDO queries. Commented Sep 13, 2014 at 6:29
  • @NoobEditor The $senderid variable is escaped using mysql_real_escape_string earlier in the code. Commented Oct 16, 2014 at 1:34

2 Answers 2

1

mysql_fetch_array does not return the whole result set, just the row at the current cursor. Your code isn't moving the mysql cursor; to do that, your code should be:

$resource = mysql_query($query, $database);
while($row = mysql_fetch_array($resource)){
  print_r($row);
  echo '<br />';
}

Also, for the desired output you posted, you should use mysql_fetch_assoc instead as it will be a hash with column names instead of an indexed array

Sign up to request clarification or add additional context in comments.

Comments

0
$query = "SELECT * FROM messages WHERE senderid IN ($senderids) ORDER BY messageid DESC";
$resource = mysql_query($query, $database);
while($result = mysql_fetch_array($resource))
{
print_r($result);    // OR $array[] = $result; and print $array outside the while loop 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.