我有一个mySQL表,其中包含如下列:
ID
-----
0352
5432
4382
3520
30593
3992
295
我想检测是否存在特定号码。
注意:此表不仅仅包含ID列。
e.g。
$num = 5432
if($num IS IN ID) {
// code
} else {
// code
}
答案 0 :(得分:4)
使用计数查询
SELECT COUNT(1) FROM `table` WHERE `ID` = 5432;
然后你可以确定......
PDO示例
$stmt = $pdo->prepare('SELECT COUNT(1) FROM `table` WHERE `ID` = ?');
$stmt->bindParam(1, $num);
$num = 5432;
$stmt->execute();
$count = $stmt->fetchColumn();
switch ($count) {
case 0 :
// does not exist
break;
case 1 :
// exists and unique
break;
default :
// exists, not unique
}
答案 1 :(得分:2)
$result = mysql_query("SELECT ID FROM table WHERE ID = '5432'");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
// number is in the table
} else {
// number is not in the table
}
答案 2 :(得分:1)
SELECT `ID`, COUNT(`ID`) AS `IS_UNIQUE` FROM `table`
GROUP BY `ID` HAVING `IS_UNIQUE` = 1;
这将返回表中恰好出现一次的所有ID。
答案 3 :(得分:0)
$result = mysqli_query("SELECT id FROM table WHERE id = {$num}");
if (mysql_num_rows($result)) {
//already exists
} else {
//does not exist
}
答案 4 :(得分:0)
那么, 您始终可以像这样执行对DB的查询:
SELECT COUNT(ID) AS cnt WHERE ID = [your id]
然后,回到php中,在获取$ row变量中的查询结果后(例如),只需仔细检查
if ($row['cnt'] > 1)