Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Check if value exists in a MySQL database

Tags:

php

mysql

exists

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.

like image 387
Hatim Avatar asked Jul 02 '12 11:07

Hatim


People also ask

How do you check if a value exists in a database?

To check whether a particular value exists in the database, you simply have to run just a regular SELECT query, fetch a row and see whether anything has been fetched.

How do you check if a column contains a value in MySQL?

$query = "SELECT * FROM my_table WHERE categories LIKE '2'"; $rows = mysql_query($query); This returns row if column only has value 2 but not 1,2,3 or 2,12.


2 Answers

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... } 
like image 62
Reinder Wit Avatar answered Sep 21 '22 20:09

Reinder Wit


For Exact Match

"SELECT * FROM yourTable WHERE city = 'c7'" 

For Pattern / Wildcard Search

"SELECT * FROM yourTable WHERE city LIKE '%c7%'" 

Of course you can change '%c7%' to '%c7' or 'c7%' depending on how you want to search it. For exact match, use first query example.

PHP

$result = mysql_query("SELECT * FROM yourTable WHERE city = 'c7'"); $matchFound = mysql_num_rows($result) > 0 ? 'yes' : 'no'; echo $matchFound; 

You can also use if condition there.

like image 25
Blaster Avatar answered Sep 19 '22 20:09

Blaster