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

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

问题描述:

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

检查所需数据是否在数据库中的正确方法是什么? p>

我目前使用的是, p>

mysql_query(“SELECT anyfield FROM table WHERE field ='$ data'”); code> p>

然后检查是否有任何行受影响。 p>

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

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

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.