php-mysqlHow to create a table in a MySQL database using PHP?
Creating a table in a MySQL database using PHP is a simple process. The following example code block will create a table called users
with three columns: id
, name
, and email
:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table users created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
The output of the example code will be:
Table users created successfully
Code explanation
$servername
,$username
,$password
,$dbname
: These variables are used to store the connection information for the MySQL database.$conn = new mysqli($servername, $username, $password, $dbname)
: This line creates a new connection to the MySQL database using the connection information stored in the variables.$sql = "CREATE TABLE users (...)
: This line creates a SQL query to create a table calledusers
with three columns:id
,name
, andemail
.if ($conn->query($sql) === TRUE)
: This line executes the SQL query to create the table.echo "Table users created successfully"
: This line prints a message to the screen if the table was created successfully.
Helpful links
More of Php Mysql
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to join tables with PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to count the number of resulting rows in a MySQL database using PHP?
- How to use a MySQL union in PHP?
- How to set a timeout for MySQL query in PHP?
- How to create an SSL connection to MySQL using PHP?
- How to get the last insert ID in PHP MySQL?
- How to fetch data from MySQL in PHP?
See more codes...