I am trying to create a database on the index page which will automatically create a database if it doesn't exist, which will then create a table and add data to it.
I am having an issue with creating the table though, it will always return:
could not create table
It creates the database with no problems, it's just the table that causing the issue. Anyone know where I'm wrong?
<?php
$servername = "localhost";
$username = "root";
$password = "admin";
$database = "jfitness";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS '($database)'";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Database already exists: " . mysqli_error($conn);
}
// make foo the current db
$db_selected = mysqli_select_db($conn, $database);
if (!$db_selected)
{
die ('Can\'t use database : ' . mysqli_error());
}
else
{
echo "Database Selected ";
}
// sql to create table
$sql = "CREATE TABLE customers( ".
"id INT NOT NULL AUTO_INCREMENT, ".
"name VARCHAR(40) NOT NULL, ".
"password VARCHAR(50) NOT NULL, ".
"email VARCHAR(50 NOT NULL), ".
"PRIMARY KEY ( id )); ";
$retval = mysqli_query($conn, $sql );
if(! $retval )
{
die('Could not create table: ' . mysqli_error());
}
echo "Table created successfully\n";
$sql = "INSERT INTO customers (username, password, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>