PHP MySQL: Create Database

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

If allartist database is not created yet, we can create it using PHP.

<?php

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

$sql = "create database allartist";
if (mysqli_query($mysqli, $sql)) {
    echo "Database allartist created successfully";
} else {
    echo "Error creating database";
}

?>

Notice how we execute the script below by passing it into mysqli_query().

create database allartist

The database connection $mysqli also needs to be passed into mysqli_query().

Its format is:

mixed mysqli_query (db_connection , query string, [int $resultmode])

If the database allartist is not available, we should get a created successfully message.  If we run the code below to create the same database, we should get an error 1007 since the DB allartist has already been created.

<?php

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

$sql = "create database allartist";
if (mysqli_query($mysqli, $sql)) {
    echo "Database allartist created successfully";
} else {
    echo "Error creating database with error no: " . $mysqli->errno;
}

?>

MySQL Clients: PHPMyAdmin

This entry is part 2 of 8 in the series MySQL Clients

First, start the WAMP server and make sure that it appears in the far right of the task bar in your Windows Desktop.

Click on it and look for PHPMyAdmin.  Start PHPMyAdmin and you will be brought to localhost/phpmyadmin in the web browser.

phpmyadmin

If this is the first time you have started using PHPMyAdmin, login as root without a password.  You will be brought to this page.

phpmyadmin1

Create Database

Click on Databases tab.

database

We will now create a database called allartist.  Type in allartist in the create database textbox and click on create.  A database allartist will be successfully created.

Create A Table

Using the code below, we will now create a table.

CREATE TABLE artist
    (
 id int auto_increment primary key, 
 artiste varchar(30), 
 album varchar(50),
 price decimal(3, 2) 
 );
 
INSERT INTO artist
(artiste, album, price)
VALUES
('Rod Stewart', 'Maggie May', 8.90 ),
('New Order', 'Substance', 7.50),
('Nirvana', 'Smell Like Teen Spirit', 9.80);

First click on allartist on the left column of the page.  Click on SQL and paste the code to the SQL query box.  Click on Go.

createtable

Go back to SQL tab and use the following query to display the table.  

select * from artist

A page will be shown as below.

query1