The function pg_query() sends SQL to the PostgreSQL installation. Again, escaping potentially dangerous characters such as single quotes is a must; this can be done with the pg_escape_string() function. In this code, you see the PHP portion of the script that accepts funny (or not-so-funny) phrases in an HTML form and writes it to the database. Sending SQL to PostgreSQL (pg_query.php; excerpt) <?php if ($db = @pg_connect('host=localhost port=5432 dbname=phrasebook user=postgres password=abc123')) { require_once 'stripFormSlashes.inc.php'; pg_query($db, sprintf( 'INSERT INTO quotes (quote, author, year) VALUES (\'%s\', \'%s\', \'%s\')', pg_escape_string($_POST['quote']), pg_escape_string($_POST['author']), intval($_POST['year']))); echo 'Quote saved.'; pg_close($db); } else { echo 'Connection failed.'; } ?> NOTE Retrieving the value in the identity column after the last INSERT statement is a bit tricky. The PostgreSQL term for such a data type is SERIAL, which automatically creates a sequence. To get the sequence's value, you can use pg_last_oid() to retrieve the oid (object id) of this value. Then, execute a SELECT id FROM quotes WHERE oid=<oid>, when <oid> is the oid you just retrieved. This finally returns the desired value. |
|