php 检查数据库中是否存在数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10119665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:25:23  来源:igfitidea点击:

Checking if data exists in database

phpmysqloptimization

提问by Kishor

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'");

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. 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?

但我对提取的数据没有任何用处anyfield。尽管这里的资源使用量很小,但在不从表中提取任何其他字段的情况下检查数据库中是否存在数据的正确方法是什么?

回答by deceze

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
}

回答by 472084

$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
}

回答by roycable

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. LIMIT 1... assuming you only want to know if anyrecord exists.

获取一个字段(我通常会这样做id)并确保您使用LIMIT,例如。LIMIT 1...假设您只想知道是否存在任何记录。

Because you're using a PHP variable to find a record, if it suits your situation, you could perhaps do a LEFT JOINon the first SQL line that gets $data, but that might just as easily be overkill for what you need.

因为您正在使用 PHP 变量来查找记录,如果它适合您的情况,您也许可以LEFT JOIN在获取 的第一行 SQL 上执行 a $data,但这对于您需要的内容来说可能很容易过度。