[英]Checking if data exists in database
What is the right way of checking if the required data is in the database? 检查所需数据是否在数据库中的正确方法是什么?
What I use currently is, 我目前使用的是
mysql_query("SELECT anyfield FROM table WHERE field='$data'");
and then check the if any rows are affected. 然后检查是否有任何行受到影响。
But I dont really have any use with the extracted data anyfield
. 但是我对提取数据的任何
anyfield
真的没有用。 Eventhough the resource usage is so minor here, what is the right way to check if data exists in a db without extracting any other fields from the table? 尽管这里的资源使用情况很小,但是在不从表中提取任何其他字段的情况下,检查数据库中是否存在数据的正确方法是什么?
Let the database count and retrieve the count data from the query. 让数据库计数并从查询中检索计数数据。
$result = mysql_query('SELECT COUNT(*) FROM `table` WHERE `field` = ...');
if (!$result) {
die(mysql_error());
}
if (mysql_result($result, 0, 0) > 0) {
// some data matched
} else {
// no data matched
}
$result = mysql_query("SELECT `field` FROM `table` WHERE `field` = '".$data."'");
if (mysql_num_rows($result)){
// Rows exist
}
OR 要么
$result = mysql_query("SELECT COUNT(`field`) as count FROM `table` WHERE `field` = '".$data."'");
$row = mysql_fetch_array($result);
if ($row ['count']){
// Rows exist
}
I would ensure, if I was checking for data, that as little data was returned as possible. 如果我要检查数据,我将确保尽可能少地返回数据。
Fetch one field (I usually do id
) and ensure you use LIMIT
, eg. 提取一个字段(我通常做
id
),并确保您使用LIMIT
,例如。 LIMIT 1
... assuming you only want to know if any record exists. LIMIT 1
...假设您只想知道是否存在任何记录。
Because you're using a PHP variable to find a record, if it suits your situation, you could perhaps do a LEFT JOIN
on the first SQL line that gets $data
, but that might just as easily be overkill for what you need. 因为您使用的是PHP变量来查找记录,所以如果适合您的情况,则可以在获取
$data
的第一行SQL上执行LEFT JOIN
,但这对于您所需的内容可能很容易被矫kill过正。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.