Validate if there is an id in the database, if there is an update and if there is no insertion to do it - PHP and postgresql

0

Good afternoon as you can see in the title, I want that at the time of entering the data to the bd of postgresql first verify that the "doc" exists, if there is an update and if there is no do an insert into , I tried and reading in forums examples but I did not leave, here I leave my code in php:

public function InsertarHuesped( $tpcli, $pais, $doctp, $doc, $docexp, $name, $lastname, $email, $phone, $address)
    {
        $Conexion = $this->Bd->connect();
        $ResultSet = $Conexion->prepare("INSERT INTO cliente1 (tpcli, country, doctp, doc, docexp, name, lastname, email, phone, address)  VALUES (:tpcli, :country, :doctp, :doc, :docexp, :name, :lastname, :email, :phone, :address)");

        $ResultSet->execute(array(
        "tpcli" => "$tpcli",
        "country" => "$pais",
        "doctp" => "$doctp",
        "doc" => "$doc",
        "docexp" => "$docexp",
        "name" => "$name",
        "lastname" => "$lastname",
        "email" => "$email",
        "phone" => "$phone",
        "address" => $address
        ));

        return $ResultSet;
    }

Thank you very much for helping me share a bit of your knowledge, good morning.

    
asked by Israel Correa Quevedo 28.05.2018 в 19:28
source

2 answers

1

What you are looking for is very similar to an upsert (update + insert). If your version of PSQL is equal to or greater than 9.5, you could run something very similar to the following:

INSERT INTO table (id, field) VALUES (1, 'foo')
  ON CONFLICT (id) DO UPDATE SET field = 'bar';
    
answered by 28.05.2018 / 20:53
source
0

I would do:

INSERT INTO table (id, field2) VALUES ('valor_id', 'val2' )
ON DUPLICATE KEY UPDATE field2 = 'val2'
    
answered by 29.05.2018 в 09:37