id | name | city
------------------
1 | n1 | c1
2 | n2 | c2
3 | n3 | c3
4 | n4 | c4
我想检查变量
city
中是否存在值为c7
的元素。
如果有,我会执行某些操作。
如果没有,我会执行其他操作。
$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
}
$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
}
$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
}
"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
条件。
PDO
或 MYSQLi
。 - Jo Smo
$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';
}
//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";
}
我尝试了一段时间,代码如下:
$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){}
它只需要一个匹配的记录就能正常工作,希望这能帮到你。
使用
select count(city) from mytable where city = 'c7'
这将仅从查询中发送单个值。如果它为0,则不存在,否则存在。由于您不会使用其他列值。
SELECT
IF city='C7'
THEN city
ELSE 'somethingelse'
END as `city`
FROM `table` WHERE `city` = 'c7'
$result = mysqli_query($conn, "SELECT * FROM WHERE = ''"; $found = mysqli_num_rows($result) > 0 ? '是' : '否' ; echo $found;
如果你正在使用 PHP 8 版本,以下是我成功的解决方案:
$result = mysqli_query(database name, "SELECT id FROM mytable WHERE city = 'c7'");
if(mysqli_num_rows($result) == 0) {
// Do Something
}
else {
// Do something else
}
我的答案和Reindeer Wit的不同之处在于'i'在mysqli_query和mysqli_num_rows()中的使用。
此外,还要在mysqli_query()中包括您正在使用的数据库名称的名称。
匹配ID:
Select * from table_name where 1=1
匹配模式:
Select * from table_name column_name Like '%string%'
LIMIT 1
会更快吗? - Ian Y.