Search code examples
phppostgresqlpdoinsertinsert-update

Overwritte data in postgresql table php


The data present in the postgresql table isn't update any more. I want to overwrite the data. When I just use insert into, new data is added but the old data remains. I tried to use update but then I get errors. I would like to update all records. I think it's probably something with the syntax. But I can't find the problem.

Code

$dbname = "dbtest";
$host = "localhost";
$username = "postgres";
$password = "pasword";

$dbh = new PDO("pgsql:dbname=$dbname; host=$host", $username, $password);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$c = array("Human","Mouse","Rat","Hamster","SV40");       
$b = array("Human HBO gene", "Mouse BB gene", "Human CCB gene", "SV40 TP gene", "Hamster TP53 gene");
$count=0;
foreach($c as $key => $d){
    $e =$b[$key];
    $name = $count++;
    if (strpos($e, $d) !== FALSE) {
        $match = $d;
        $specie = $d;
        $specie = str_replace("Human","Homo Sapiens",$specie);
        $specie = str_replace("Mouse","Mus Musculus",$specie);
        $specie = str_replace("Rat","Rattus norvegicus",$specie);
        $Specie = str_replace("Hamster", "Mesocricetus Auratus",$specie);
        $specie = str_replace("SV40","Simian virus 40",$specie);
    }else{
        $match = "0";
        $specie = "0";
    }

echo $match. " ". $specie. " ";

$var_id = $name;
$var_match = $match;
$var_full_name = $specie;


    #$sql = "INSERT INTO species (id,match,full_name) VALUES ('".$var_id."','".$var_match ."','".$var_full_name."')";
    $sql = "UPDATE species SET id = '".$var_id."', match = '".$var_match ."', full_name='".$var_full_name."'";
    if ($dbh->query($sql)) {
        echo "New Record Inserted Successfully!<br \>\n";
    }else{
        echo "Data not successfully Inserted.<br \>\n";
    } 
}

The error I get:

Fatal error: Uncaught PDOException: SQLSTATE[42601]: Syntax error: 7 ERROR: > syntax error at or near "Sapiens" LINE 1: ...species SET id = '0', match = Human, full_name=Homo Sapiens' ^ in /var/www/html/test/Insert.php:59 Stack trace: #0 /var/www/html/test/Insert.php(59): PDO->query('UPDATE species ...') #1 {main} thrown in /var/www/html/test/Insert.php on line 59


Solution

  • When I use the following syntax, the error is gone. This query needs to be used to update.

    $sql = "UPDATE species SET match ='".$var_match ."', full_name='".$var_full_name."' WHERE id = '".$var_id."' ";