How to Check if a Record Exists in a MySQL Database

  1. The Correct Command
  2. A Common Mistake
  3. What is MySQL

Almost everyone has been in a circumstance when it is necessary to check whether a record exists in the MySQL database or not.

Let’s look through how to do that with the most suitable and easy command. Below you can find the right command and a common mistake that almost every beginner can make while trying to figure out the problem.

The Correct Command

If you want to check whether a record already exists in your database or not, you should run the following code:

$query = "SELECT * FROM products WHERE code = '$code'";
$result = mysql_query($query);
if ($result) {
  if (mysql_num_rows($result) > 0) {
    echo 'found!';
  } else {
    echo 'not found';
  }
} else {
  echo 'Error: '.mysql_error();
}

A Common Mistake

Now, let’s check out a common mistake that we recommend you to overcome:

//Will NOT work
$query = "SELECT * FROM products WHERE code = '$code'";
$result = mysql_query($query);
if ($result) {
  echo 'found';
} else {
  echo 'not found';
}

What is MySQL

MySQL is considered an open-source relational database management system. It is aimed at organizing data into one or more data tables.

Several popular applications such as Twitter, Facebook YouTube, Google apply MySQL for data storage purposes. It was initially made for limited usage. Yet, now it is compatible with many essential computing platforms such as macOS, Linux Ubuntu, and Microsoft Windows.


Do you find this helpful?

Related articles