-2

quick question:

How to check if row already exists in mysql?

I know some will suggest mysql_num_rows(), which I've tried and no good.

Here's the PHP code:

...

$chk = mysql_query("SELECT * FROM f_table WHERE f = '$id' AND h = 'h' AND status = '1'");

if(mysql_num_rows($chk) > 0){
    $msg = 'exist';
}else{
            $msg = 'gotta';
    }

Ps: I just noticed that the php manual suggested us to use some else instead of 'mysql_num_rows()', and my mysql version is 5.0. Is it related?

Thank u for ur time.

Matt
  • 565
  • 1
  • 7
  • 12
  • 2
    Why does it not work? It should. – deceze Dec 11 '12 at 15:42
  • 3
    Please stop using this code. `mysql_` functions are being [deprecated](http://www.deprecatedphp.com/mysql). You should use `mysqli_` or `PDO` instead. It's also poor practice to `SELECT *`; always specify a column list. – Kermit Dec 11 '12 at 15:43
  • 1
    This sould work, maybe your sql statement is incorrect – Philippe Boissonneault Dec 11 '12 at 15:43
  • @deceze Yep, sorry for that! I just find out why. I've got some errors in my query... Sorry for wasting ur time. – Matt Dec 11 '12 at 15:44
  • possible duplicate of [Best way to test if a row exists in a MySQL table](http://stackoverflow.com/questions/1676551/best-way-to-test-if-a-row-exists-in-a-mysql-table) –  Jun 14 '15 at 18:38

2 Answers2

1

If you're not going to use the rows, just do a SELECT COUNT(*) FROM .... Otherwise, mysql_num_rows should work, even if this API is deprecated.

Thomas Ruiz
  • 3,611
  • 2
  • 20
  • 33
1

Typically you'd want to let MySQL do the counting instead of fetching all rows. MySQL can use indexes and doesn't have to retrieve all data, which may be a lot more efficient:

$result = mysql_query('SELECT COUNT(*) as `count` FROM ...') /* or die(mysql_error()) */;
$row = mysql_fetch_assoc($result);

if ($row['count'] ...)
deceze
  • 510,633
  • 85
  • 743
  • 889