Create Table using PDO Object

How to create table using PDO in PHP?

Explanation

Once the database connection is established we can do basic operations like create, insert, select, delete and update.

Create Table: Syntax
$createTable = $db->exec("CREATE TABLE IF NOT EXISTS tablename (columns)");

Here,we call the exec() method of the PDO class to execute the SQL statements in sequence. The exec() method returns the number of affected rows, including 0, on success and false on failure.

Example :

$createTable = $db->exec("CREATE TABLE IF NOT EXISTS user_details (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(200) NOT NULL,
last_name VARCHAR(200) NOT NULL,
email VARCHAR(200) NOT NULL
)");

Result :
pdo-create
In the above example, table "user_details" is created with field name like id, first_name, last_name and email. Here, we assigned primary key to the field name id (i.e) a primary key is used to identify a unique record in a database table.

PHP Topics


Ask Questions

Ask Question