Re: pg_query won't execute

Поиск
Список
Период
Сортировка
От Tom Lane
Тема Re: pg_query won't execute
Дата
Msg-id 28648.1520195976@sss.pgh.pa.us
обсуждение исходный текст
Ответ на pg_query won't execute  ("Dale Schmitz" <dschmitz4@cox.net>)
Список pgsql-novice
"Dale Schmitz" <dschmitz4@cox.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


В списке pgsql-novice по дате отправления:

Предыдущее
От: "Dale Schmitz"
Дата:
Сообщение: pg_query won't execute
Следующее
От: Max Fomichev
Дата:
Сообщение: GIN, pg_trgm and large table