Re: pg_query won't execute

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Dale Schmitz" <dschmitz4(at)cox(dot)net>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: pg_query won't execute
Date: 2018-03-04 20:39:36
Message-ID: 28648.1520195976@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

"Dale Schmitz" <dschmitz4(at)cox(dot)net> writes:
> The statement "SELECT COUNT(*) FROM users WHERE username = 'john' works just
> fine in the pgAdmin query tool, but not like this:

> $sql = "SELECT COUNT(*) FROM users WHERE username = $username";

What you're presumably ending up with is a query string like

SELECT COUNT(*) FROM users WHERE username = john

which isn't going to work ... unless there's a column named "john" in
"users", and even then it probably doesn't produce the result you
intended. You need to quote the inserted value as a literal.

But really the better way would be to insert "john" as a parameter.
If you do something like this:

$sql = "SELECT COUNT(*) FROM users WHERE username = '$username'";

it'd appear to work, until you ran into a username containing a single
quote. (You've heard of SQL injection, right?) I don't know PHP, so
I'm not sure whether it provides any convenient way to produce a safely
escaped literal equivalent of an arbitrary input string. But I'm almost
sure it will let you do something along the lines of

$sql = "SELECT COUNT(*) FROM users WHERE username = ?";

and then separately transmit the value to be used for the parameter
symbol.

regards, tom lane

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Alvaro Herrera 2018-03-05 17:25:39 Re: STATISTICS retained in CREATE TABLE ... LIKE (INCLUDING ALL)?
Previous Message Dale Schmitz 2018-03-04 20:10:27 pg_query won't execute