假设我有这张桌子:
id | name | city
------------------
1 | n1 | c1
2 | n2 | c2
3 | n3 | c3
4 | n4 | c4
我想检查c7
变量下是否存在该值city
。
如果是这样,我会做点什么。
如果没有,我会做其他事情。
首选方式,使用 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...
}
"SELECT * FROM yourTable WHERE city = 'c7'"
"SELECT * FROM yourTable WHERE city LIKE '%c7%'"
当然,您可以更改'%c7%'
为'%c7'
或'c7%'
取决于您要如何搜索它。对于完全匹配,使用第一个查询示例。
$result = mysql_query("SELECT * FROM yourTable WHERE city = 'c7'");
$matchFound = mysql_num_rows($result) > 0 ? 'yes' : 'no';
echo $matchFound;
您也可以if
在那里使用条件。
假设连接已建立并且在全局范围内可用;
//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";
}
SELECT
IF city='C7'
THEN city
ELSE 'somethingelse'
END as `city`
FROM `table` WHERE `city` = 'c7'
我尝试了一段时间,
如果有两个相同的条目就可以工作,但是,如果你用它替换
它只
适用于一个匹配的记录,希望这会有所帮助。 $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){}
用于匹配 ID:
Select * from table_name where 1=1
对于匹配模式:
Select * from table_name column_name Like '%string%'
这对我有用:
$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';
}
采用
select count(city) from mytable where city = 'c7'
这将只从查询中发送一个值。如果为 0,则不存在,否则存在。由于您不会使用其他列值。