41

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.

Panos
  • 1,764
  • 21
  • 23
Hatim
  • 1,516
  • 1
  • 18
  • 30

10 Answers10

74

preferred way, using MySQLi extension (supported from PHP 5 onwards):

$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 and not supported in PHP 7 or newer:

$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...
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Reinder Wit
  • 6,490
  • 1
  • 25
  • 36
  • 3
    Wouldn't be better to use SQL's EXISTS statement like http://stackoverflow.com/a/1676573/204634 ? – lorenzog Mar 15 '16 at 17:24
  • Speed-wise, would it be faster by adding `LIMIT 1`? – Ian Y. Jun 01 '18 at 02:56
  • 2
    @IanY. that depends on the query but usually yes. Have a look at this: https://stackoverflow.com/questions/455476/does-adding-limit-1-to-mysql-queries-make-them-faster-when-you-know-there-will – Reinder Wit Jun 01 '18 at 06:40
18

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.

Blaster
  • 9,414
  • 1
  • 29
  • 25
1

Assuming the connection is established and is available in global scope;

//Check if a value exists in a table
function record_exists ($table, $column, $value) {
    global $connection;
    $query = "SELECT * FROM {$table} WHERE {$column} = {$value}";
    $result = mysql_query ( $query, $connection );
    if ( mysql_num_rows ( $result ) ) {
        return TRUE;
    } else {
        return FALSE;
    }
}

Usage: Assuming that the value to be checked is stored in the variable $username;

if (record_exists ( 'employee', 'username', $username )){
    echo "Username is not available. Try something else.";
} else {
    echo "Username is available";
}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Hari
  • 25
  • 7
1

This works for me :


$db = mysqli_connect('localhost', 'UserName', 'Password', 'DB_Name') or die('Not Connected');
mysqli_set_charset($db, 'utf8');

$sql = mysqli_query($db,"SELECT * FROM `mytable` WHERE city='c7'");
$sql = mysqli_fetch_assoc($sql);
$Checker = $sql['city'];

if  ($Checker != null) {
    
    echo 'Already exists';
    
} else {

    echo 'Not found';
}

CrazyMind90
  • 11
  • 1
  • 2
0
SELECT
    IF city='C7'
    THEN city
    ELSE 'somethingelse'
    END as `city`
FROM `table` WHERE `city` = 'c7'
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
0

I tried to d this for a while and $sqlcommand = 'SELECT * FROM database WHERE search="'.$searchString.'";';
$sth = $db->prepare($sqlcommand); $sth->execute(); $record = $sth->fetch(); if ($sth->fetchColumn() > 0){}
just works if there are TWO identical entries, but, if you replace if ($sth->fetchColumn() > 0){} with if ($result){} it works with only one matching record, hope this helps.

mushkincode
  • 67
  • 1
  • 7
0

use

select count(city) from mytable where city = 'c7'

This will send only a single value from the query. If it is 0 it is not present else it is present. Since you will not be use the other column values.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
-1

For Matching the ID:

Select * from table_name where 1=1

For Matching the Pattern:

Select * from table_name column_name Like '%string%'
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
-1

$result = mysqli_query($conn, "SELECT * FROM WHERE = ''"; $found = mysqli_num_rows($result) > 0 ? 'Yes' : 'no' ; echo $found;

  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 21 '22 at 08:55
-1

Here's is what worked with me if you're using PHP Version 8

$result = mysqli_query(database name, "SELECT id FROM mytable WHERE city = 'c7'");      
  
  if(mysqli_num_rows($result) == 0) {
       // Do Something 
  }
  else {
      // Do something else 
  }

The difference with my answer and Reindeer Wit is the 'i' in mysqli_query and mysqli_num_rows()

Also including the name of the database name inside of mysqli_query() that you are using.

Adan Vivero
  • 422
  • 12
  • 36
  • 1
    "I figured that Reinder Wit answer is a bit outdated" — It isn't. It has two sections. The first section is marked **preferred** and is supported from PHP 5 onwards. You were trying to follow the section marked **deprecated** which is **not** supported since PHP 7. – Quentin Oct 08 '22 at 21:43