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

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?

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.