Jump to content

[SOLVED] query database for existence of an id


Dragen

Recommended Posts

okay... I'm trying to do a query to my database where it checks if an id exists. If it does it performs an update to the database, whereas if it doesn't it adds to the database instead...

This is the code I've got:

$sql = "SELECT * FROM committee WHERE id = '".$id['0']."'";
if($result = mysql_query($sql)){
	// update code here if it find the id in the database
}else{
	// insert code here if new id
}

I thought that would work as it checks the database for id where it's equal to my $id variable, then if it doesn't find the matching id in the databse surely it should output the else statement?

mysql_query() returns a result if the query was successfull, not nesescarily if it found a record.

 

<?php

$sql = "SELECT * FROM committee WHERE id = '".$id['0']."'";
  if ($result = mysql_query($sql)) {
    if (mysqlnum_rows($result)) {
      // found $id in database.
    } else {
      // $id not found.
    }
  } else {
    // query failed.
    echo mysql_error();
  }

?>

 

$id['0'] also is suss. It should either be $id[0] if its an array, or simply $id for a variable.

where is result actually being set? surely it would always be true

 

anyway wouldnt it be best or maybe simplest to check num_rows on the query then if num rows > 0 use the id else insert a new id and use last insert id as the id (if you still need it)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.