php sql的问题没有选择数据库

时间:2016-11-07 20:31:50

标签: php mysql sql

我已经创建了数据库CSCW,我不确定为什么我一直收到错误,'没有选择数据库'我是初学者所以任何帮助都是奖金!谢谢!

<html>
<head>
<title>CS coursework</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1>Online Stock Help.</h1>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "CSCW";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

//create db tables
$sql = "CREATE TABLE users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    businessName VARCHAR(30) NOT NULL,
    name VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    regDate TIMESTAMP
)
";
if (mysqli_query($conn, $sql)) {
    echo "Table Created Successfully";
}  else {
    echo "Unsuccessful: " . mysqli_error($conn);
}

?>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

正确的代码是:

<html>
<head>
<title>CS coursework</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1>Online Stock Help.</h1>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "CSCW";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

//create db tables
$sql = "CREATE TABLE users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    businessName VARCHAR(30) NOT NULL,
    name VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    regDate TIMESTAMP
)
";
if (mysqli_query($conn, $sql)) {
    echo "Table Created Successfully";
}  else {
    echo "Unsuccessful: " . mysqli_error($conn);
}

?>

</body>
</html>

答案 1 :(得分:0)

您的连接缺少数据库名称 将连接线更改为 $ conn = new mysqli($ servername,$ username,$ password,$ dbname);