I know how to make a database in PDO , but I am having a problem with making a 'check'. I need to to read if you do not have 'this' database (where database could be mydb), then create it and then echo out "mydb created successfully."
If there is already a database with that name then echo out "mydb found". Like I said I am using PDO here. I will show what I have thus far. I will also include how I am putting in a check to make the tables that I will need also.
Thank you in advance for any help!
<?php
//Database creation
require_once 'core/init.php';
$servername = Config::get('mysql/host');
$username = Config::get('mysql/username');
$password = Config::get('mysql/password');
$dbname = Config::get('mysql/db');
$createtable = false;
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE IF NOT EXISTS $dbname";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
$createtable = true;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
$createtable = true;
} else {
echo Config::get('mysql/db'). '- found!';
}
//Table1 creation
if($createtable){
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// sql to create table
$table = 'surveys';
$sql = "CREATE TABLE IF NOT EXISTS $table (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(20) NOT NULL,
password VARCHAR(64) NOT NULL,
last_name VARCHAR(20) NOT NULL,
first_name VARCHAR(20) NOT NULL,
middle_name VARCHAR(20),
address_1 VARCHAR(32) NOT NULL,
address_2 VARCHAR(32),
city VARCHAR(32) NOT NULL,
state VARCHAR(12) NOT NULL,
zip INT(12) NOT NULL,
salt VARCHAR(32) NOT NULL
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "Table {$table} created successfully";
//Table2 creation
$table = 'users_session';
$sql = "CREATE TABLE IF NOT EXISTS $table (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
user_id INT(11) NOT NULL,
hash VARCHAR(64) NOT NULL,
)";
$conn->exec($sql);
echo "Table {$table} created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
} else {
echo "Tables are already made and ready to go!";
}
?>