我目前正在努力完成作业。我将创建一个PHP脚本,它将创建一个数据库和该数据库的所有表。我已经能够通过阅读这里和W3School来拼凑脚本以创建数据库本身,但是我很难过如何在新数据库上创建相同的脚本创建表。这就是我创建新数据库所需要的:
<?php
$servername = "localhost";
$username = "root";
$password = "mysql";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE IF NOT EXISTS musicDB";
$conn->exec($sql);
echo "DB created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
我试着按照这个来创建表格:
<?php
$servername = "localhost";
$username = "root";
$password = "mysql";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE IF NOT EXISTS musicDB";
$sql = "use musicDB";
$sql = "CREATE TABLE IF NOT EXISTS ARTISTS (
ID int(11) AUTO_INCREMENT PRIMARY KEY,
artistname varchar(30) NOT NULL)";
$conn->exec($sql);
echo "DB created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
然而,这不起作用,我得到以下错误:CREATE TABLE IF NOT EXISTS ARTISTS(ID int(11)AUTO_INCREMENT PRIMARY KEY,artistname varchar(30)NOT NULL) SQLSTATE [3D000]:无效的目录名称:1046未选择数据库
基本上,我如何告诉脚本使用新创建的表然后为它创建表?我知道用户名和密码正在显示,但这是在我的笔记本电脑上运行,永远不会在任何地方,所以我并不担心。
答案 0 :(得分:8)
你只是在执行最后一个语句。您继续分配给$sql
,但不执行这些陈述。
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE IF NOT EXISTS musicDB";
$conn->exec($sql);
$sql = "use musicDB";
$conn->exec($sql);
$sql = "CREATE TABLE IF NOT EXISTS ARTISTS (
ID int(11) AUTO_INCREMENT PRIMARY KEY,
artistname varchar(30) NOT NULL)";
$conn->exec($sql);
echo "DB created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
答案 1 :(得分:0)
相反,尝试将所有这些语句包装在一个过程中,并从您的代码中调用它,如
str_replace