我正在尝试在数据库中创建一个表。数据库test
存在,我收到错误No database selected
。我相信我使用代码$select_db = mysql_select_db($database);
以下是代码:
$host_name = 'localhost';
$user_name = 'root';
$password = '';
$database = "test";
$connection = mysqli_connect($host_name,$user_name,$password);
$select_db = mysql_select_db($database);
if ($select_db) {
echo "Database found <br>";
# code...
}
else
{
echo "Database not found <br>";
}
//code Working correctly till DATABASE FOUND.
$sql = "CREATE TABLE employee (employee_id INT(4) NOT NULL PRIMARY KEY AUTO_INCREMENT , Name CHAR(30) NOT NULL)";
if (mysqli_query($connection,$sql))
{
# code...
echo "Table created successfully";
}
else
{
echo "Table not created with the following error<br><strong>".mysqli_error($connection)."</strong>";
}
/*$db_close = mysql_close($Connection);
if ($db_close) {
echo "Connection closed";
# code...
}
else
{
echo "Connection not closed";
}*/
?>
答案 0 :(得分:2)
$connection = mysqli_connect($host_name,$user_name,$password);
VS
$select_db = mysql_select_db($database);
看起来非常接近:)找到一个 i ,这会让一切变得与众不同。
找到错误后,请再次访问 mysqli_connect 文档,了解如何为其提供数据库名称。用1块石头杀死2只鸟。
答案 1 :(得分:0)
您正在混合mysql
和mysqli
个扩展程序。不推荐使用mysql
。仅使用mysqli
或PDO
。
// mysqli here
$connection = mysqli_connect($host_name,$user_name,$password);
// and mysql here
$select_db = mysql_select_db($database);
更改为
$select_db = mysqli_select_db($database);
答案 2 :(得分:-1)
您实际上只是检查$select_db
是否为空。
在数据库连接上运行查询之前,您必须连接到它。
这是我一直在使用的示例课程。
<?php
class database{
// Database settings
protected $_mysqli = false;
protected $_db = array(
"username" => "username here",
"password" => "password here",
"host" => "localhost",
"database" => "database name here",
"charset" => "utf8"
);
// Function to connect to the database
function connect() {
$mysqli = new mysqli($this->_db['host'], $this->_db['username'], $this->_db['password'], $this->_db['database']);
if ( $mysqli->connect_errno ) {
$this->_mysqli = false;
}else {
$mysqli->set_charset($this->_db['charset']);
$this->_mysqli = $mysqli;
}
}
// Function to execute an sql query
function execute_query($sql) {
if ( $results = $this->_mysqli->query($sql) ) {
return $results;
}else {
return false;
}
}
}
?>
您可以连接到数据库并运行如下所示的查询:
<?php
//Includes the class file
require_once('database.php');
// Connects to the database
$database_connection = new database();
// To execute a sql query
$query_response = $database_connection->execute_query("SELECT * FROM table");
?>
但是你实际上从未连接到你的数据库。