11.2. Inserting and Retrieving Data

Connecting to the database is just not enough. In this section you will learn how to communicate with the database, how to create tables, and how to insert and retrieve data.

The first thing to do is to create a new table. Therefore you can write a short PHP script:

<?php
        $connstr = "dbname=phpbook user=postgres host=localhost";
        $dbh = pg_connect($connstr);
        if ($dbh) {echo "connection to phpbook established ...<br>";}

        $sql = "CREATE TABLE person (id serial, name text, location text)";
        $stat = pg_exec($dbh, $sql);
        if      ($stat)
        {
                echo "The table has successfully been created<br>\n";
        }
        else
        {
                echo "creating the table failed<br>\n";
        }
        pg_close($dbh);
?>

After connecting to the database, a string containing the ...

Get PHP and PostgreSQL: Advanced Web Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.