I am running this script which looks at inputs $area1 and $area2 and checks them against my database, if they are not then it inputs them. This is what I have written but I'm new to PHP and it's not working, not only that I believe there is a better way to do this but I'm unsure of a more efficient solution.
$query1 = "SELECT location_name FROM locations WHERE (location_name = '$area1')";
$connect->query($query1);
if ($partner_result = $connect->query($query1)) {
$partner_row = $partner_result->fetch_row();
if(!empty($partner_row)) {
$partners = $partner_row;
print_r($partners);
} else {
$insert_location = "INSERT INTO locations (location_id, location_name) VALUES (NULL, '".$area1."')"
$connect->query($insert_location);
echo "Location added<br>";
$partners = false;
}
$partner_result->close();
} else {
$get_partners = false;
}
$query3 = "SELECT location_name FROM locations WHERE (location_name = '$area2')";
$connect->query($query2);
if ($partner_result = $connect->query($query2)) {
$partner_row = $partner_result->fetch_row();
if(!empty($partner_row)) {
$partners = $partner_row;
print_r($partners);
} else {
$insert_location = "INSERT INTO locations (location_id, location_name) VALUES (NULL, '".$area2."')"
$connect->query($insert_location);
echo "Location added<br>";
$partners = false;
}
$partner_result->close();
} else {
$get_partners = false;
}
mysqlior PDO or something else?->query()twice for the top-levelif()calls? All that does is waste a bunch of cpu time. and if you want to check for dupes, you're going about it wrong - you're building race-condition code. There'sinsert ... on duplicate key updatefor a reason.location_idis your primary key and potentially using an autoincrement? If so, you'll need a unique index onlocation_namefor the on duplicate key mentioned in comments and answers.