ON CONFLICT using the error name pg_prepare () does not exist

I have a simple DB class with this method

function __construct($host, $user, $pass, $db) {
    $this->link = pg_connect("host=$host port=5432 dbname=$db user=$user password=$pass") or $this->error();
}

public function run($sql, $args = null) {
    if(!$args)
        $this->query = pg_query($sql);
    else {
        $v = md5(uniqid(mt_rand(), true));
        $this->query = pg_prepare($v, $sql);
        $this->query = pg_execute($v, $args);
    }
    return $this;
}

      

Using this, I can execute the following query without prepared statements and it works great.

$db->run("
    INSERT INTO userExercise (userid, exerciseid, date, sets)
    VALUES ($user->id, $exerciseid, '$date', '$sets')

    ON CONFLICT (userid, date, exerciseid)
    DO UPDATE SET sets = '$sets'

    RETURNING LASTVAL()"
);

      

However, when I do prepared, I get the error "ERROR: prepared statement" 41982c47c3c84749552cd9808ad03422 "does not exist"

    $db->run("
        INSERT INTO userExercise (userid, exerciseid, date, sets)
        VALUES ($1, $2, $3 $4)

        ON CONFLICT (userid, date, exerciseid)
        DO UPDATE SET sets = $4

        RETURNING LASTVAL()",
        [$user->id, $exerciseid, $date, $sets]
    );

      

41982c47c3c84749552cd9808ad03422

as a result md5

, to give a unique name. The problem is related to ON CONFLICT

. How can I fix this?

+3


source to share


1 answer


you are not checking the result from pg_prepare and there is probably a syntax error. For example, VALUES ($1, $2, $3 $4)

must have one more comma.



Also, RETURNING LASTVAL()

should probably be something like RETURNING ID

, or whatever you call your sequential column. Otherwise, you will get bogus results for the conflict case.

+3


source







All Articles