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 calleduserswith 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 output XML from MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to use a MySQL union in PHP?
- How to change database in MySQL with PHP?
- How to generate a UUID in MySQL using PHP?
- How to insert a null value in MySQL using PHP?
- How to escape JSON in PHP and MySQL?
- How to use a variable in a MySQL query using PHP?
- How to fetch an associative array from MySQL in PHP?
- How to convert MySQL datetime to string in PHP?
See more codes...