0

pg_query can't be executed in the case where name = ' Kill 'em all ' the error is pointing at the " ' " before "em" which is the problem but i can't find a solution.

$query = "INSERT INTO order (foodid,name) VALUES ($food_id,'$food')";
$result = pg_query($conn,$query) or die("Query cannot be executed");
prof chaos
  • 404
  • 3
  • 18
  • it is because that particular name contains `'` to pass it to database query should be replaced with `\'`. If you got problems here you should really take look on topic of "SQL Injection" and SQL queries with parameters to avoid further headaches. – MoreThanChaos Jan 17 '16 at 03:22

1 Answers1

1

Right now you're passing the string

INSERT INTO order (foodid,name) VALUES (1,' Kill 'em all')

to the postgresql server, which has no chance to determine that the ' in 'em is part of the string literal and not its delimiter.
You have to make sure your payload parameters do not "break" the sql statement.

You can do that either by using the appropriate encoding/escaping function for string literals to put the payload directly into the sql statement

// <--- test whether $food_id contains only digits here, e.g. via ctype_digit
$query = sprintf('
    INSERT INTO
        order (foodid,name)
    VALUES
        (%s,%s)',
    $food_id, pg_escape_literal($conn, $food)
);

$result = pg_query($conn,$query) or die("Query cannot be executed");

or using a prepared statement + parameters, in effect separating the actual sql statement from the payload data:

// Prepare a query for execution
$result = pg_prepare($conn, '', '
    INSERT INTO
        order (foodid,name)
    VALUES
        ($1,$2)
');
if ( !$result ) {
    yourErrorHandler();
}
$result = pg_execute($conn, '', array($food_id, $foo));
if ( !$result ) {
    yourErrorHandler();
}

see also: http://php.net/security.database.sql-injection

VolkerK
  • 95,432
  • 20
  • 163
  • 226