How to Check if value exists in a MySQL database

Hatim picture Hatim · Jul 2, 2012 · Viewed 210.3k times · Source

Suppose I have this table:

id | name | city
------------------
1  | n1   | c1
2  | n2   | c2
3  | n3   | c3
4  | n4   | c4

I want to check if the value c7 exists under the variable city or not.

If it does, I will do something.
If it doesn't, I will do something else.

Answer

Reinder Wit picture Reinder Wit · Jul 2, 2012

preferred way, using MySQLi extension:

$mysqli = new mysqli(SERVER, DBUSER, DBPASS, DATABASE);
$result = $mysqli->query("SELECT id FROM mytable WHERE city = 'c7'");
if($result->num_rows == 0) {
     // row not found, do stuff...
} else {
    // do other stuff...
}
$mysqli->close();

deprecated:

$result = mysql_query("SELECT id FROM mytable WHERE city = 'c7'");
if(mysql_num_rows($result) == 0) {
     // row not found, do stuff...
} else {
    // do other stuff...
}