tags:

views:

144

answers:

5

Im trying to write a function to check whether a user exists in a table, if so, update the row, if not, insert it.

Here is my function:

     function UserExists($screenname){
      $mysql = mysql_fetch_array ( mysql_query("SELECT * FROM `users` WHERE `screenname` = '$screenname' "));
       if($mysql){
        return TRUE;
       }else{
        return FALSE;
       }
}

And im executing this function using the following:

if(UserExists($user)){
mysql_query("UPDATE `users` SET  `token` =  '$token' ,  `secret` =  '$secret'  WHERE `screenname` = '$user' ");
}else{
mysql_query("INSERT INTO `users` (`screenname`, `token`, `secret`) VALUES ('$user', '$token', '$secret')");
}

Its not doing anything, not throwing any errors, but also not updating the table.

A: 
mysql_query('..query..') or die(mysql_error());
Mike B
errors in mysql statement syntax does not get displayed on the screen.you should use debugging messages, like Mike suggested, to see what's going on.
phunehehe
A: 

Call mysql_error after the calls to see what error you are getting. Also another good debugging technique is to execute it on the server using a mysql client such as mysqlfront or myphpadmin

Toby Allen
+3  A: 

You'd want to take a look at the INSERT ... ON DUPLICATE KEY UPDATE ... MySQL query syntax to make this work with just one query.

INSERT INTO users (screenname, token, secret) VALUES ('screenname', 'token', 'secret')
ON DUPLICATE KEY UPDATE token = 'token', secret = 'secret'

screenname should be unique (or a primary key) which you probably don't have at the moment. I suggest to add an ID column in your database table and use that to refer to database rows.

JoostK
A: 

Your best solution is ON DUPLICATE KEY as JoostK stated

Webnet
A: 

I'd simply suggest to use REPLACE INTO SET col = val in this case, all you need to do is define a unique index on the table.

The Replace Command will have a look at the unique indexes, if a row already exists it will update the existing, if not it will insert a new one.

Bobby

Bobby