如果没有重复PHP / SQL,请检查条目并插入

时间:2015-11-09 17:01:33

标签: php mysql

我正在运行这个查看输入$ area1和$ area2的脚本,并根据我的数据库检查它们,如果不是则输入它们。这就是我所写的,但我是PHP的新手而且它不起作用,不仅我认为有更好的方法来做到这一点,但我不确定更有效的解决方案。

$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;
}

1 个答案:

答案 0 :(得分:3)

您可以在数据库端实现它,而不涉及太多PHP

首先,您需要在&#34; location_name&#34;上使用 UNIQUE index 。柱:

CREATE UNIQUE INDEX location_name_index ON locations (location_name)

然后您可以随时执行insert ignore 只有在尚未存在的情况下才会添加新位置

INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '".$area1."')
INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '".$area2."')

此外,您的代码中不清楚您是否有secured your inputs。如果你有 - 好!如果你还没有这样做:

$query1 = sprintf("INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '%s')",mysql_real_escape_string($area1));