user1939481
user1939481

Reputation: 69

php does not execute a well formed posqtgresql sentence

i have this code:

$dbconn = pg_connect("host=localhost dbname=dbbase user=postgres password=postgres") or die('Connection error: ' . pg_last_error());
$qstation ="SELECT id FROM st WHERE string ='".$string."'";
$rstation = pg_query($dbconn,$qstation) or die('Query error: ' . pg_last_error());

echo $qstation;

this shows me

SELECT id FROM st WHERE string='A_AA_00_00_A'

if i execute it on pgadmin3, it returns me the result.

but if i try to do

print_r(pg_fetch_array($rstation, null, PGSQL_ASSOC));

i have no erros and print_r() does not return me anything.

if i change the $string variable with 'A_AA_00_00_A'

$qstation ="SELECT id FROM st WHERE string='A_AA_00_00_A'";

the sentence executes right and print_r() returns data

Array ( [id] => 10 )

what am i doing wrong?

Upvotes: 0

Views: 67

Answers (1)

Craig Ringer
Craig Ringer

Reputation: 324731

You really should be using parameterized statements here, though I see no reason to think that's the problem in this specific case. Use PDO, or pg_query_params. See http://bobby-tables.com, google "SQL injection", PHP manual on SQL injection.

In a case like this you really need to look at the PostgreSQL server error logs to determine whether the query is reaching PostgreSQL at all, and if it is, whether it's failing with an error.

You also appear to be failing to properly check for errors in your PHP code. Use pg_result_status to test for an error, and pg_result_status to get error specifics.

$rstation = pg_query($dbconn,$qstation) or die('Query error: ' . pg_last_error());
if (pg_result_status($rstation) != PGSQL_TUPLES_OK) {
    $errmsg = pg_result_error($rstation);
    # ... report error to user or handle it ...
}

You might also want to look at pg_result_error_field for specific error fields.

Upvotes: 1

Related Questions