我知道如何在PDO中创建数据库,但是我在进行“检查”时遇到了问题。如果你没有'this'数据库(数据库可能是mydb),我需要阅读,然后创建它,然后回显出“mydb已成功创建。”
如果已经存在具有该名称的数据库,则回显“mydb found”。 就像我说我在这里使用PDO。我将展示到目前为止我所拥有的一切。我还将包括如何制作支票以制作我需要的表格。
提前感谢您的帮助!
<?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!";
}
?>
答案 0 :(得分:0)
您可以使用SHOW TABLES
:
$sql = "SHOW TABLES LIKE 'tableName'";
$tableExists = $conn->query($sql)->rowCount() > 0;
if( !$tableExists ){
//create table
}