robert wersaq
robert wersaq

Reputation: 39

How to check data in mysql using limit?

How to check data in mysql using limit ?

When load this code (will check data in row id 2) , it's echo requests field

Why not echo not requests field

this is test_table:

________________________________
|  id  |  pro_id  |  requests  |
|  1   |  11111   |     0      |
|  2   |  12345   |     0      |
|  3   |  12345   |     0      |
|  4   |  12345   |     1      |
|__5___|__12345___|_____1______|

and this is php code for check data in test_table

<?PHP
    include("connect.php");
    $i = "0";

    $sql = "SELECT * FROM test_table WHERE pro_id = '12345' AND requests != '0' order by id asc limit $i,1";
    $query = mysql_query($sql);
    $result = mysql_fetch_array($query);
    if($result)
        echo "requests field";
    else
        echo "not requests field";
?>

Upvotes: 0

Views: 84

Answers (2)

mirza.adipradhana
mirza.adipradhana

Reputation: 421

Your PHP script will generate a query like this SELECT * FROM test_table WHERE pro_id = '12345' AND requests != '0' order by id asc limit 0,1 . And the query output will be like this:

+----+---------+----------+
| id | prod_id | requests |
+----+---------+----------+
| 4  | 12345   | 1        |
+----+---------+----------+

So, your PHP script :

if($result)
    echo "requests field";
else
    echo "not requests field";

is always returns true value, because your query with your specific condition will found a record, which means $result has true value.

FYI: if a query returns an empty record which is empty array, it will return a false value

I assume that you want to know that, id=2 record is exist or not while specific condition assigned. So you might modified your PHP script like this:

if($result){
   if($result["id"]==2) 
      echo "requests field";
   else
      echo "not requests field";
}
else
    echo "not requests field";

Hope it helps.

Upvotes: 1

Prashant Srivastav
Prashant Srivastav

Reputation: 1743

Because $result is result-set it have 0 rows

if(array)
    true;
   else
    false;

it will always return true. because empty array is never equal FALSE;

Upvotes: 1

Related Questions