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’ll create two new tables in the stocks database: stocks and stock_evaluations with the following structures:
We create a new class named PostgreSQLCreateTable in the app folder.
How it works.
First, the constructor of the class accepts a PDO object as the argument.
Second, the createTables() method creates 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.
In the index.php file, connect to the PostgreSQL database execute the statement to create tables and query tables.
Launch the index.php file in a web browser. You’ll see the following output:
The output shows that the script has created two tables successfully.
Summary
Use the CREATE TABLE statement to create a new table.
Use the PDO exec() method to to execute a CREATE TABLE statement to create a new table in the datatabase.