How to Check if value exists in a MySQL database

后端 未结 6 707
眼角桃花
眼角桃花 2020-12-12 17:15

Suppose I have this table:

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

I want to check

6条回答
  •  难免孤独
    2020-12-12 18:10

    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";
    }
    

提交回复
热议问题