How to Check if a Record Exists in a MySQL Database

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.

Watch a course Learn object oriented PHP

The Correct Command

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

Using MySqli

<?php

// connect to database
$mysqli = new mysqli("localhost","db_user","db_password","db_name");

$query = "SELECT * FROM products WHERE code = '$code'";

$result = $mysqli->query($query);

if ($result) {
    if (mysqli_num_rows($result) > 0) {
        echo 'found!';
    } else {
        echo 'not found';
    }
} else {
    echo 'Error: ' . mysqli_error();
}

// close connection
mysqli_close($mysqli);

?>

Using mysql (deprecated)

<?php

$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:

<?php

//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.