Visualizer7
Visualizer7

Reputation: 325

To check if a certain row with certain value exists in table

I wrote this code and it works, but I'm still wondering if there is any other solution which is better and simpler.

$sql = "select * from db_member where username = '$name'";
$result = mysql_query($sql) or error(mysql_error());
if(mysql_num_rows($result) < 1) 
{
error("There is no user with name '$name'.");
}

Upvotes: 1

Views: 119

Answers (2)

ivodvb
ivodvb

Reputation: 1164

A faster way to do it:

$result = mysql_query("SELECT COUNT(1) FROM db_member WHERE username='".mysql_real_escape_string($name)."'") or die(mysql_error());
if (mysql_result($result, 0) == 0) {
    echo 'There is no user with name ' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '.';
}

Please check http://php.net/pdo for better error handling and query parameters....

I think using mysql_query this way shoulnd't be done anymore..

Upvotes: 0

Sebas
Sebas

Reputation: 21542

No, without any other detail this is a good solution. However you could have a look at the following points:

  • take care of your indexes. If you could use a where clause on some indexed columns it would be perfect
  • if you plan to check the existence of an element before insertion, i'ld rather catch the error than checking like you're doing.
  • you could indeed reduce overhead reducing the selection range, like mentionned by another member

rgds

Upvotes: 2

Related Questions