Jump to content

MySQL Check for any value


Lamez

Recommended Posts

also you can try to check the resource type if it's empty.

 

$result=mysql_query($q);

if(empty($result)) or you may be checking $result == flase.... i am not sure which one is correct kindly try and see whether its useful or not.

 

 

regards

 

That will only show that the query was successful, not if it returned any results. There is a difference.

Your question is pretty unclear. Do you want to know if the row exists? Or wether a particular field has a value. Either way, mysql_num_rows is your friend.

 

Check to see if a row with an id of 1 exists.

<?php

  $sql = "SELECT foo FROM tbl WHERE id = 1";
  if ($result = mysql_query($sql)) {
    if (mysql_num_rows($result)) {
      // row exists.
    } else {
      // row does not exist
    }
  }

?>

 

Check if the orw with an id of 1 contains a value in field foo.

<?php

  $sql = "SELECT foo FROM tbl WHERE id = 1 && foo <> ''";
  if ($result = mysql_query($sql)) {
    if (mysql_num_rows($result)) {
      // row exists.
    } else {
      // row does not exist
    }
  }

?>

I got it, thanks to some logical thinking, and the mysql_num_rows

 

here is my function:

<?php
  function barView($var, $table){
     $num = mysql_num_rows(mysql_query("Select `$var` From `$table`"));
     if ($num >= 1){
  echo "there is somthing in the table";
 }else{
  echo "nothing in the table";
 }
  }
?>

 

in my other page:

 

<?php
barView(a1, rnd1);
?>

 

 

Much better coded as....

 

<?php

  function barView($var, $table) {
    $sql = "SELECT `$var` FROM `$table`";
    if ($result = mysql_query($sql)) {
      return mysql_num_rows($result);
    }
    return false;
  }
  
  if (barView('a1', 'rnd1')) {
    echo "there is somthing in the table";
  } else {
    echo "nothing in the table";
  }

?>

In your code, this line here....

 

$num = mysql_num_rows(mysql_query("Select `$var` From `$table`"));

 

Is vulnerable to errors. You make no attempt to check that mysql_query() returns a result resource before using it in mysql_num_rows(). mysql_num_rows() expects a result resource, anything else will make it throw an error.

 

As for the rest, I simply removed the checking logic into the calling code. Notice that most php functions return true or false? So should yours. This makes your functions allot more usable in different situations. I very rarely have a function echo anything.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.