如何检查MySQL数据库中是否存在值

时间:2012-07-02 11:10:19

标签: php mysql exists

假设我有这张表:

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

我想检查变量c7下是否存在值city

如果确实如此,我会做点什么 如果没有,我会做别的事情。

7 个答案:

答案 0 :(得分:61)

首选方式,使用MySQLi扩展名:

$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();

弃用:

$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...
}

答案 1 :(得分:15)

完全匹配

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

用于模式/通配符搜索

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

当然,您可以将'%c7%'更改为'%c7''c7%',具体取决于您要搜索的方式。要获得完全匹配,请使用第一个查询示例。

PHP

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

你也可以在那里使用if条件。

答案 2 :(得分:2)

假设已建立连接且可在全局范围内使用;

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

使用方法: 假设要检查的值存储在变量$ username;

if (record_exists ( 'employee', 'username', $username )){
    echo "Username is not available. Try something else.";
} else {
    echo "Username is available";
}

答案 3 :(得分:0)

SELECT
    IF city='C7'
    THEN city
    ELSE 'somethingelse'
    END as `city`
FROM `table` WHERE `city` = 'c7'

答案 4 :(得分:0)

我试着用了一段时间     $sqlcommand = 'SELECT * FROM database WHERE search="'.$searchString.'";';
$sth = $db->prepare($sqlcommand); $sth->execute(); $record = $sth->fetch(); if ($sth->fetchColumn() > 0){}
如果有两个相同的条目,只是工作,但是, 如果你更换     if ($sth->fetchColumn() > 0){} 同     if ($result){} 它只适用于一个匹配的记录,希望这会有所帮助。

答案 5 :(得分:0)

用于匹配ID:

Select * from table_name where 1=1

用于匹配模式:

Select * from table_name column_name Like '%string%'

答案 6 :(得分:0)

这对我有用:


$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';
}