开发者

Postgres INSERT INTO query bug?

What's wrong with the following Postgres query?

INSERT INTO kayak.airports(name, x, y, city) VALUES开发者_运维问答( $name, $x, $y, $city) 
WHERE airport_id='$airport_id

EDIT (thanks Donnie for helping me make progress) : I tried:

$query="UPDATE kayak.airports SET name=$name, x = $x, y = $y, city = $city
WHERE airports.airport_id='$airport_id'"; 

It said "column 'Brisbane' doesn't exist" (Brisbane is the first city to be inserted. ) I took out everything between SET and WHERE except for "x=$x" and those were successfully inserted. Ditto for "y=$y". When only leaving in name=$name it says

"Query failed: ERROR: syntax error at or near "International" LINE 1: UPDATE kayak .airports SET name=Brisbane International WHERE... ^"


Your query string is not quoted. Do not use PHP variable interpolation for building SQL queries, because this will leave your script or application vulnerable to an SQL injection attack.

Instead, use parameterized queries. Thus, your query above becomes:

$query = 'UPDATE kayak.airports SET name = $1, x = $2, y = $3, city = $4'.
         'WHERE airports.airport_id = $5';

Then, you will use the parameterized query calling function pg_query_paramsto pass the required parameters:

$result = pg_query_params($query, $parameters)

Where $parameters is an array of parameters.

Also note that the $query string is single-quoted, because the $n placeholders are not there for interpolation. This prevents any mistakes (such as typing a real variable name by bumping a letter first) and eliminates any possibility of SQL injection.


You're attempting to insert literal values. A where clause makes no sense.

For insert, you can only use where in an insert ... select to limit what the select is returning.

Perhaps you actually want to update an existing record?


For me, if I get an error that a column doesn't exist, it's usually a tipoff that I've quoted something incorrectly (or not at all).

This is borne out by the error message from your attempt to update only the name field:

ERROR: syntax error at or near "International" LINE 1:

(The carat should point right to the problem area in the query.)

The value you are passing to the name field in your UPDATE statement needs to be quoted, just like the value you're passing to airport_id. (I'm going to take a wild guess that x and y are integers, which wouldn't require quoting, which is why you don't get an error when you try to update just those field.) (I'm going to take another wild guess that the value you pass to city will need to be quoted too, but you will probably figure that out shortly. :) )

The end result expanded UPDATE should look something like this:

UPDATE kayak.airports
SET name='Brisbane International', x = 123, y = 456, city = 'Brisbane'
WHERE ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜