Dragen Posted April 30, 2007 Share Posted April 30, 2007 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? Link to comment https://forums.phpfreaks.com/topic/49310-solved-query-database-for-existence-of-an-id/ Share on other sites More sharing options...
trq Posted April 30, 2007 Share Posted April 30, 2007 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. Link to comment https://forums.phpfreaks.com/topic/49310-solved-query-database-for-existence-of-an-id/#findComment-241630 Share on other sites More sharing options...
map200uk Posted April 30, 2007 Share Posted April 30, 2007 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) Link to comment https://forums.phpfreaks.com/topic/49310-solved-query-database-for-existence-of-an-id/#findComment-241631 Share on other sites More sharing options...
map200uk Posted April 30, 2007 Share Posted April 30, 2007 ahh beaten to it:) Link to comment https://forums.phpfreaks.com/topic/49310-solved-query-database-for-existence-of-an-id/#findComment-241633 Share on other sites More sharing options...
Dragen Posted April 30, 2007 Author Share Posted April 30, 2007 ah thanks. It's always the simple things that I forget... just needed the if (mysql_num_rows($result)) { thanks! I'm still learning... Link to comment https://forums.phpfreaks.com/topic/49310-solved-query-database-for-existence-of-an-id/#findComment-241643 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.