在PHP / SQL中选择数据库

时间:2015-03-27 14:56:30

标签: php mysql sql database xampp

// sql to create table
$sql = "CREATE TABLE unpw (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
username VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
)";

if ($conn->query($sql) === TRUE) {
    echo "Table unpw created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}

我是SQL和PHP的新手,并且一直致力于将一些python和C++代码转换为PHP,并为我的项目使用SQL服务器,并且它正在抛出一个错误

Error creating table: No database selected”(谢谢错误处理)。

如何选择数据库?

我试过编辑它说:

$sql = "USE myDB;
CREATE TABLE unpw (

等等,但我得到了错误:

"Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TABLE unpw ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, username' at line 2"

有任何帮助吗?感谢。

2 个答案:

答案 0 :(得分:0)

您是否尝试过将$ servername更改为此?

$servername  = "mysql:host=localhost;dbname=myDb"

答案 1 :(得分:0)

将此添加到顶部,用您的

更改详细信息
$DBServer = 'server name or IP address'; // e.g 'localhost' or '192.168.1.100'
$DBUser   = 'DB_USER';
$DBPass   = 'DB_PASSWORD';
$DBName   = 'DB_NAME';

$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);