Search code examples
phpsqlpostgresqlpg-query

pg_query error because of name: 'kill 'em all'


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");

Solution

  • 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