Wednesday, April 23, 2025

MySQLi Create Database

create_database.php


<?php
//Config

$server = "localhost";
$user = "root";
$password = "";

//Establishing a Connection to MySQL Server
$connection = mysqli_connect($server, $user, $password);

//Check Connection
if (!$connection) {
	die("<h2>Total Fail</h2> " . mysqli_connect_error());
} else {
	echo "Connection Successfull <br>";
}

//SQL Command
$sql_command = "CREATE DATABASE address_book";

//Check SQL Command
if (mysqli_query($connection, $sql_command)) {
	echo "DATABASE CREATED";
} else {
	echo "SQL ERROR" . mysqli_error($connection);
}

?>

This code is creating a new MySQL database named "address_book" using the mysqli_query() function. Here is what each line of the code does:

  1. $sql_command = "CREATE DATABASE address_book"; - This line defines a SQL command that will create a new database named "address_book".
  2. if (mysqli_query($connection, $sql_command)) { - This line checks if the SQL command was successfully executed using the mysqli_query() function. The $connection variable holds the connection object to the MySQL server that was established earlier.
  3. echo "DATABASE CREATED"; - This line will be printed to the screen if the database creation is successful.
  4. else { echo "SQL ERROR" . mysqli_error($connection); } - If the SQL command fails, this line will be executed and will print an error message that includes the error message returned by the mysqli_error() function.

After first run:


Connection Successfull
DATABASE CREATED

After second run:


Connection Successfull
SQL ERROR Can't create database 'address_book'; database exists

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...