0

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.

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Your best solution is ON DUPLICATE KEY as JoostK stated

Comments

0

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 phpMyAdmin.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.