Carbon Posted August 17, 2011 Share Posted August 17, 2011 Hi, just wondering how would I make the query UPDATE instead of INSERT if there is a duplicate entry on one key (Username) The error would be: Failed Duplicate entry 'Carbon' for key 'Username' Thanks! Link to comment https://forums.phpfreaks.com/topic/245064-php-mysql-if-table-exists-update/ Share on other sites More sharing options...
dougjohnson Posted August 17, 2011 Share Posted August 17, 2011 One way to do this would be to search for a match for the username. If a match exists, UPDATE. If a match does not exist, INSERT. $usernamematch = "Carbon"; $result = $connection->prepare("SELECT username FROM tablename WHERE username = ?"); $result->bind_param("s", $username); $result->execute(); $result->bind_result($usernamefound); while ($row = $result->fetch()) { } if ($usernamefound != "") { } else { } Link to comment https://forums.phpfreaks.com/topic/245064-php-mysql-if-table-exists-update/#findComment-1258738 Share on other sites More sharing options...
Maq Posted August 17, 2011 Share Posted August 17, 2011 You can use REPLACE INTO. If the record exists (PKs), it will update, otherwise insert. Link to comment https://forums.phpfreaks.com/topic/245064-php-mysql-if-table-exists-update/#findComment-1258741 Share on other sites More sharing options...
Carbon Posted August 17, 2011 Author Share Posted August 17, 2011 Just seen something else, the update function isn't what I was looking for I don't think, I have a program and I want to keep stats of users in a database for uses such as highscores and dynamic images, so for example, page is: update.php?user=usernamehere&credits=2000&time=00:30:00 What I want it todo is if it isn't a duplicate username then it will insert if not it will add the credits gained onto what is currently there, same with time ran (in hh:mm:ss format) Link to comment https://forums.phpfreaks.com/topic/245064-php-mysql-if-table-exists-update/#findComment-1258746 Share on other sites More sharing options...
fenway Posted August 17, 2011 Share Posted August 17, 2011 You're looking for INSERT... ON DUPLICATE KEY UPDATE. Link to comment https://forums.phpfreaks.com/topic/245064-php-mysql-if-table-exists-update/#findComment-1258831 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.