如果不是EXISTS,则INSERT else显示消息不起作用

时间:2015-07-11 08:54:48

标签: php postgresql

我有一张表'参考'在其中,我们的想法是,如果已经存在引用,那么它就不会插入。如果它不存在则会插入。但是这段代码并没有插入任何一种方式。请帮助。

$dbconn = pg_connect("host=127.0.0.1 dbname=XX user=XX password=XX") or die('Could not connect: ' . pg_last_error());
$query = "IF NOT EXISTS (SELECT reference FROM card WHERE reference = '$reference')
INSERT INTO staff (reference, first_name, last_name, address1, address2, address3, address4)
VALUES ('$reference', '$first_name', '$last_name', '$address1', '$address2', '$address3', '$address4')";

$result = pg_query($query);
    if (!$result)  
{  
echo "Customer update failed!! This ID might already be registered with us. Please go back and check the spelling of your email address.<br><br><input type=\"button\" value=\"Go Back\" onClick=\"history.go(-1);return true;\">"; 
die; 
} else  
{  
echo "Customer update successful; ";  
}  

pg_close(); 

2 个答案:

答案 0 :(得分:3)

制作column as Unique。然后插入并不要担心该行的存在。如果它已经存在,则返回FALSE。

答案 1 :(得分:1)

try{
    $db = new PDO("pgsql:dbname=yourdbname charset=utf8","username","password");
    $query=$db->prepare("
        insert into staff (
            reference, first_name, last_name,
            address1, address2, address3, address4
        )
        select * from (
            select ? as reference, ?, ?, ?, ?, ?, ?
        ) as _
        where reference not in (select reference from staff)
    ");
    $insert = $query->execute(array(
        $reference, $first_name, $last_name,
        $address1, $address2, $address3, $address4
    ));
    if ($insert->rowCount() == 0) {
        echo "ERROR: Customer already exists!";
    } else {
        echo "Customer account creation successful!";
    }
} catch(PDOException $e) {
    echo "Error: ".$e;
}