1

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?

4

2 回答 2

0

您没有转义引号符号'。您有 2 个选项。

第一次用反斜杠转义它们:

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

第二(建议)只需使用heredoc符号:

$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;

这里的例子。

||是 Postgres 的连接运算符。我认为你有错字和这条线

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

有错字,应该是

n.last_name || '', '' || n.first_name AS "Full Name"
于 2019-03-22T15:12:32.837 回答
0

您在由单引号分隔的字符串中有单引号:

'SELECT * FROM foo WHERE id = '123''

你需要逃离他们。IIRC,Postgres 使用双打来做到这一点:

'SELECT * FROM foo WHERE id = ''123'''

或者也许是反斜杠:

'SELECT * FROM foo WHERE id = \'123\''
于 2019-03-22T15:12:30.533 回答