PostgreSQL Tutorial

  • Home
  • Administration
  • Views
  • Triggers
  • Stored Procedures
  • Interfaces
    • PostgreSQL PHP
    • PostgreSQL Python
    • PostgreSQL JDBC
Home / PostgreSQL PHP / PostgreSQL PHP: Create New Tables

PostgreSQL PHP: Create New Tables

Summary: in this tutorial, you will learn how to create new tables in the PostgreSQL database using PHP PDO API.

Creating new tables using PHP PDO steps

To create new tables in a PostgreSQL database using PHP PDO, you use the following steps:

  1. First, connect to the database by creating a new PDO object.
  2. Second, call the exec() method of the PDO object to execute the CREATE TABLE statement.

Let’s look at an example of creating new tables.

Creating new table example

In the previous tutorial, we created the stocks database in the PostgreSQL database server. For the demonstration, we will create two new tables in the stocks database: stocks and stock_evaluations with the following structures:

1
2
3
4
5
CREATE TABLE IF NOT EXISTS stocks (
    id SERIAL PRIMARY KEY,
    symbol CHARACTER VARYING(10) NOT NULL UNIQUE,
    company CHARACTER VARYING(255) NOT NULL UNIQUE
);

1
2
3
4
5
6
7
8
CREATE TABLE IF NOT EXISTS stock_valuations (
    stock_id INTEGER NOT NULL,
    value_on DATE NOT NULL,
    price NUMERIC(8 , 2 ) NOT NULL DEFAULT 0,
    PRIMARY KEY (stock_id , value_on),
    FOREIGN KEY (stock_id)
        REFERENCES stocks (id)
);

We create a new class named PostgreSQLCreateTable in the app folder.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
 
namespace PostgreSQLTutorial;
/**
* Create table in PostgreSQL from PHP demo
*/
class PostgreSQLCreateTable {
 
    /**
     * PDO object
     * @var \PDO
     */
    private $pdo;
 
    /**
     * init the object with a \PDO object
     * @param type $pdo
     */
    public function __construct($pdo) {
        $this->pdo = $pdo;
    }
 
    /**
     * create tables
     */
    public function createTables() {
        $sqlList = ['CREATE TABLE IF NOT EXISTS stocks (
                        id serial PRIMARY KEY,
                        symbol character varying(10) NOT NULL UNIQUE,
                        company character varying(255) NOT NULL UNIQUE
                     )',
            'CREATE TABLE IF NOT EXISTS stock_valuations (
                        stock_id INTEGER NOT NULL,
                        value_on date NOT NULL,
                        price numeric(8,2) NOT NULL DEFAULT 0,
                        PRIMARY KEY (stock_id, value_on),
                        FOREIGN KEY (stock_id) REFERENCES stocks(id)
                    );'];
 
        // execute each sql statement to create new tables
        foreach ($sqlList as $sql) {
            $this->pdo->exec($sql);
        }
        
        return $this;
    }
 
    /**
     * return tables in the database
     */
    public function getTables() {
        $stmt = $this->pdo->query("SELECT table_name
                                   FROM information_schema.tables
                                   WHERE table_schema= 'public'
                                        AND table_type='BASE TABLE'
                                   ORDER BY table_name");
        $tableList = [];
        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            $tableList[] = $row['table_name'];
        }
 
        return $tableList;
    }
}

How it works.

  • First, the constructor of the class accepts a PDO object as the argument.
  • Second, the createTables() method is in charge of creating new tables in the database. The $sqlList array holds all the CREATE TABLE statements. To execute a statement, you call the exec() method of the PDO object. We iterate over the array of SQL statements and execute them one by one by calling the exec() method.
  • Third, the getTables() method returns all tables in the connected database. We use it to query the tables in the stocks database after calling the createTables() method.

PostgreSQL PHP Create Tables

In the index.php file, we connect to the PostgreSQL database, execute the statement to create tables, and query tables in the database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
 
require 'vendor/autoload.php';
 
use PostgreSQLTutorial\Connection as Connection;
use PostgreSQLTutorial\PostgreSQLCreateTable as PostgreSQLCreateTable;
 
try {
    
    // connect to the PostgreSQL database
    $pdo = Connection::get()->connect();
    
    //
    $tableCreator = new PostgreSQLCreateTable($pdo);
    
    // create tables and query the table from the
    // database
    $tables = $tableCreator->createTables()
                            ->getTables();
    
    foreach ($tables as $table){
        echo $table . '<br>';
    }
    
} catch (\PDOException $e) {
    echo $e->getMessage();
}

Launch the index.php file in a web browser, we get the following output:

1
2
stock_valuations
stocks

It means that we have created these two tables successfully from the PHP application. In the next tutorial, we will show you how to insert data into these tables using PHP PDO API.

Previous Tutorial: PostgreSQL PHP: Connect to PostgreSQL Database Using PDO
Next Tutorial: PostgreSQL PHP: Insert Data Into Tables

PostgreSQL Quick Start

  • What is PostgreSQL?
  • Install PostgreSQL
  • Connect to Database
  • Download PostgreSQL Sample Database
  • Load Sample Database
  • Explore Server and Database Objects

PostgreSQL PHP

  • Connect to PostgreSQL Database Using PDO
  • Create New Tables in PHP
  • Insert Data Into Tables in PHP
  • Update Data In a Table using PDD
  • Handle Transaction in PHP
  • Query Data From PostgresQL using PDO
  • Call PostgreSQL Stored Procedures in PHP
  • Manage with BLOB in PHP
  • Delete Data From a Table in PHP

About PostgreSQL Tutorial

PostgreSQLTutorial.com is a website dedicated to developers and database administrators who are working on PostgreSQL database management system.

We constantly publish useful PostgreSQL tutorials to keep you up-to-date with the latest PostgreSQL features and technologies. All PostgreSQL tutorials are simple, easy-to-follow and practical.

Recent PostgreSQL Tutorials

  • PostgreSQL Recursive View
  • Learn PostgreSQL Recursive Query By Example
  • Creating Updatable Views Using the WITH CHECK OPTION Clause
  • PostgreSQL Upsert Using INSERT ON CONFLICT statement
  • How to Generate a Random Number in A Range
  • Using PostgreSQL ADD COLUMN to Add One or More Columns To a Table
  • PostgreSQL Character Types: CHAR, VARCHAR, and TEXT
  • Using PostgreSQL SERIAL To Create Auto-increment Column
  • PostgreSQL Boolean Data Type with Practical Examples
  • Understanding PostgreSQL Timestamp Data Types

More Tutorials

  • PostgreSQL PHP
  • PostgreSQL Python
  • PostgreSQL JDBC
  • PostgreSQL Functions
  • PostgreSQL Resources

Site Info

  • Home
  • About Us
  • Contact Us
  • Privacy Policy

Copyright © 2017 by PostgreSQL Tutorial Website. All Rights Reserved.