PHP MySQL: Create Table

This entry is part 5 of 17 in the series PHP & MySQL

In this sqlfiddle, we have created a table and inserted some data into the table.

CREATE TABLE artist
	(
 id int auto_increment primary key, 
 artiste varchar(30), 
 album varchar(50),
 year int(10)
 
 );

INSERT INTO artist
(artiste, album, year)
VALUES
('Rod Stewart', 'Maggie May', 1973),
('New Order', 'Substance', 1987),
('Nirvana', 'Smell Like Teen Spirit', 1992);
Run the SQL

Let’s create this similar table using PHP.  Using PHP, a table is created by mysqli_query.

There are 2 parameters in mysqli_query.  The database connection string $mysqli and the create table string $sql.

<?php

$mysqli = new mysqli("localhost", "root", "", "allartist");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL";
}

$sql = "CREATE TABLE artist (id int auto_increment primary key, artiste varchar(30), album varchar(50), year int(10))";

if (mysqli_query($mysqli, $sql)) {
    echo "Table artist created successfully";
} else {
    echo "Error creating table with error no: " . $mysqli->errno;
}

?>

If the WAMP server in your PC is started, you can try to run the above script.  If an error number is generated, you can google the relevant error message.

You can now login to phpMyAdmin and see the table artist similar to the screenshot below.

artist_table

Series Navigation<< PHP MySQL: Create Database
PHP MySQL: Insert Record >>