phppostgresqlselectpgadminphp-pgsql

PHP Select From Postgres Unexpected Character


I have an application written in PHP, I'm connecting to a PGSQL database and selecting some data. This works as expected until I use the string concatenation operator (||) in the query.

I connected tothe PGSQL db via PGadmin and generated the query, so I know it definitely works. I then copied the code and pasted it into my $query variable.

My code is below;

$dbconn = pg_connect("host=xxx dbname=xxx user=xxx password=xxx") or die('Could not connect: ' . pg_last_error());
$query = ' 
SELECT
f.date_gmt::date as "Date Assessed"
n.last_name || ', '' || n.first_name AS "Full Name" // line 12
FROM
fines as f
JOIN
record_metadata as r
ON
r.id = f.record_metadata_id
JOIN
fullname as n
ON
n.id = f.record_metadata_id
';

$result = pg_query($query) or die('Query failed: ' . pg_last_error());

echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

pg_free_result($result);
pg_close($dbconn);

The error produced is;

Parse error: syntax error, unexpected ',' in /...index.php on line 12

Removing line 12 from the code resolves the issue. But, I need this data so what do I need to change in order to achieve what I want?

Presumably I can't simply copy the working query from the PGSQL db and paste it into my PHP code?


Solution

  • You did not escape quote symbols '. You have 2 options.

    1st escape them with back slashes:

    n.last_name || \', \'\' || n.first_name AS "Full Name"
    

    2nd (suggested) Just use heredoc notation:

    $query = <<<QUERY
    SELECT
    f.date_gmt::date as "Date Assessed"
    n.last_name || ', '' || n.first_name AS "Full Name"
    FROM
    fines as f
    JOIN
    record_metadata as r
    ON
    r.id = f.record_metadata_id
    JOIN
    fullname as n
    ON
    n.id = f.record_metadata_id
    QUERY;
    

    Example here.

    || is concatenation operator for Postgres. I think you have typo there and this line

    n.last_name || ', '' || n.first_name AS "Full Name"
    

    has a typo, should be

    n.last_name || '', '' || n.first_name AS "Full Name"