0

I am trying to check if entry belongs to database or not.

$result = mysql_query("SELECT Lot# FROM data WHERE Lot#='$batch'");
if(mysql_num_rows($result) == 0) {
     echo "Batch# does not exist. please enter a valid batch#";
     }
     else {
    header("Location: http://localhost/EasyTrack/std Order1.php"); /* Redirect browser */
}

What happens, in both cases, if entry belongs or does not belong to database it shows:

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\EasyTrack\StdOrderUpdate.php on line 28 Batch# does not exist. please enter a valid batch#

Is my way of checking correct? if not what's a better way to do so?

Sahar Alsadah
  • 2,412
  • 3
  • 18
  • 24

2 Answers2

0

There are many aspects potentially wrong with your code (security speaking). But taking for granted that this is just an example code, according to the PHP documentation:

mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query

Moreover '#' are not allowed as column names. Assuming you intended to do that, surround those names with backticks.

FURTHER NOTES:

  1. MySQL extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used
  2. Since you are using a variable directly in the query make sure it is safe. Either escape it or use prepared statements
mjsarfatti
  • 1,615
  • 1
  • 15
  • 21
0

In this, or any similar case, where you don't know whats wrong with query, You should use mysql_error(). It returns the text of the error message from previous MySQL operation.

Updated based upon your comment

// First, you have to establish connection with database.
mysql_connect($host, $username, $password) or die("Cannot connect to database");

// Next, select database that you want to work with.
mysql_select_db($db_name) or die("cannot select database");

// Then, finally, start using it.
$result = mysql_query("SELECT Lot# FROM data WHERE Lot#='$batch'") or die(mysql_error());

Refer mysql_connect and mysql_select_db for more details.

Note: This is just for quick debugging purpose. Do not use in production.

Bhavik Shah
  • 2,250
  • 1
  • 16
  • 32