Im not very experienced in PHP and would appreciate any help! Im am sending a username, longitude and latitude to my server using HTTP Post. I first check if the user exists in the user_info table. If it does then i try to update the maps_user_location table with that username. What i want to happen is that if the query fails, due to the username not being found in maps_user_location table, then i want it to be added. I’ve tried to do it with the code below.
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$username = $_POST['username'];
if ($latitude != 0 && $longitude != 0) {
$query_userCheck = "SELECT * FROM user_info WHERE login_username = '".$username."';";
if ( mysql_query($query_userCheck) ) {
$query_updateLocation = "UPDATE `maps_user_location` SET `lat` = '".$latitude."',`long` = '".$longitude."' WHERE
`login_username` = '".$username."';";
if ( !mysql_query($query_updateLocation) ){
$query_newLocation = "INSERT INTO `maps_user_location` ( `id` ,`login_username` ,`lat` ,`long` ,`track`)
VALUES ( NULL , '".$username."', '".$latitude."', '".$longitude."', '0');";
mysql_query($query_newLocation);
}
}
}
When i execute the code, it goes through without a hitch. The problem is that a row is never inserted if the username does not exist already, the row does update if the username exists though. Additionally, when i add a row manually, the id column seems to increment after every request (the sequence will go 1,2,3,4,10,11,12…etc [the ids 5-9 do not exist]). I have a feeling that it has to do with the ‘WHERE’ in ‘$query_updateLocation’. Anyone have any clue as to why this happens?
You can simply do that in a single query, Use
INSERT...ON DUPLICATE KEY UPDATEbut before anything else, make sure that you have a
UNIQUE CONSTRAINTon the columnlogin_username. If you have not added, you can alter your table using this command