36

假设我有这张桌子:

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

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

如果是这样,我会做点什么。
如果没有,我会做其他事情。

4

8 回答 8

70

首选方式,使用 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...
}
于 2012-07-02T11:16:06.043 回答
18

精确匹配

"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在那里使用条件。

于 2012-07-02T11:11:26.937 回答
1

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

//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";
}
于 2016-02-11T05:01:17.143 回答
0
SELECT
    IF city='C7'
    THEN city
    ELSE 'somethingelse'
    END as `city`
FROM `table` WHERE `city` = 'c7'
于 2012-07-02T11:14:51.810 回答
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){}

于 2014-08-20T05:34:01.770 回答
0

用于匹配 ID:

Select * from table_name where 1=1

对于匹配模式:

Select * from table_name column_name Like '%string%'
于 2019-04-09T10:36:26.943 回答
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';
}

于 2021-01-01T15:43:44.497 回答
0

采用

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

这将只从查询中发送一个值。如果为 0,则不存在,否则存在。由于您不会使用其他列值。

于 2021-09-13T05:07:03.077 回答