PHP doesn't fetch all rows from my database query

325 Views Asked by At

I have this code below:

if(isset($_POST['period'])){
    $query_str = "SELECT `id` FROM `orders` WHERE `status` = 'Send' AND `date` BETWEEN '".date('Y-m-d H:i:s', time()-$_POST['period'])."'  AND  '".date('Y-m-d H:i:s', time())."'  ";
    echo $query_str;
    $query = mysql_query($query_str) or die(mysql_error());
    $arr = mysql_fetch_assoc($query);
    var_dump($arr);

}

As result I have these two strings:

// this value of $query_str
SELECT `id` FROM `orders` WHERE `status` = 'Send' AND `date` BETWEEN '2015-06-04 03:11:08'  AND  '2015-06-11 03:11:08' 

// var_dump of my $arr
array(1) {
  ["id"]=>
  string(2) "25"
} 

This result is wrong, but when I am copying $uqery_str value and put it into phpMyAdmin I have 3 results.

25,26,27 // this is right

Can anybody explain what is wrong?

1

There are 1 best solutions below

2
On BEST ANSWER

That is because you only fetch the first row. Put your fetch call into a while loop to fetch all rows, e.g.

$arr = mysql_fetch_assoc($query);
var_dump($arr);

to:

while($arr = mysql_fetch_assoc($query)) {
    var_dump($arr);
}

$query is a resource and with mysql_fetch_assoc() you fetch row by row from the resource. As from the manual:

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.

Also since we are here I give you a good night story for today:

mysql_* is deprecated and is removed in new versions of PHP. So I would highly recommend you to look into PDO or mysqli_* prepared statements.