Search code examples
phpsqlpostgresqlinsertinsert-update

New and old values in postgresql php


I have a table containing lots of data. In this table I would like to add new and update old values. Therefore, I found the following method

After adapting the query from the response, I still got an error.

Fatal error: Uncaught PDOException: SQLSTATE[42702]: Ambiguous column: 7 
ERROR: column reference "id" is ambiguous LINE 3: ...richia coli',full_name = 
'Escherichia coli' WHERE id = '0' ^ in /var/www/html/Insert.php:127 Stack 
trace: #0 /var/www/html/Insert.php(127): PDO->query('INSERT INTO spe...') #1 
{main} thrown in /var/www/html/Insert.php on line 127

The adapted query is :

$sql = "INSERT INTO species (id,match,full_name)
VALUES ('".$var_id."','".$var_match ."','".$var_full_name."')".
"ON CONFLICT (id) DO UPDATE 
SET match = '".$var_match."',full_name = '".$var_full_name."' ". 
" WHERE id = '".$var_id."' ";

For some reason it still doesn't seem to recognise ON CONFLICT (id) DO UPDATE SET. See pictureenter image description here Could someone tell me were I got it wrong? Thanks in advance.


Solution

  • This is the solution I found. I split the query into because the ON CONFLICT wasn't working for me. First I use select to determine if row already exist by checking if id is present. If id is present the data is update. If the idea is not present a new row is added.

    Function

    function execute_query($query,$dbh){
        if ($dbh->query($query)) {
            return "New Record Inserted Successfully!<br \>\n";
        }else{
            return "Data not successfully Inserted.<br \>\n";
        } 
    } 
    

    Select and prepare statement

    $query = 'SELECT * FROM species '. 'WHERE id = '. "'".$var_id."'";
    
    $stmt = $dbh->prepare($query);
    $stmt->execute();
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $out = $stmt->fetch();
    print_r($out) ;
    

    If result => update row

    if ($out !== false){
        $sql = "UPDATE species SET id = '".$var_id."', match ='".$var_match."',full_name = '".$var_full_name."'
        WHERE id = '".$var_id."' ";
        echo $sql ."<br \>\n";;
        execute_query($sql,$dbh); # function
        echo "Value is updated";
    
    }else{ ### If no result => insert new values
        $sql = "INSERT INTO species (id,match,full_name)VALUES 
        ('".$var_id."','".$var_match ."','".$var_full_name."')";
        execute_query($sql,$dbh);
        echo "New value is inserted";