Search code examples
phpmysqlexists

How to Check if value exists in a MySQL database


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.


Solution

  • using modern MySQLi:

    $mysqli = new mysqli(SERVER, DBUSER, DBPASS, DATABASE);
    
    $city = 'c7';
    $result = $mysqli->execute_query("SELECT id FROM mytable WHERE city = ? LIMIT 1", [$city]);
    if($result->num_rows == 1) {
        // found
    }
    

    using legacy mysqli

    $mysqli = new mysqli(SERVER, DBUSER, DBPASS, DATABASE);
    
    $city = 'c7';
    $stmt = $mysqli->prepare("SELECT id FROM mytable WHERE city = ? LIMIT 1");
    $stmt->bind_param("s", $city);
    $stmt->execute();
    $result = $stmt->get_result();
    if($result->num_rows == 1) {
        // found
    }
    

    using PDO:

    $pdo = new PDO($dsn, $user, $pass, $options);
    
    $city = 'c7';
    $stmt = $pdo->prepare("SELECT id FROM mytable WHERE city = ? LIMIT 1");
    $stmt->execute([$city]);
    if($stmt->rowCount() == 1) {
        // found
    }