2016-03-02 49 views
-1

我试图在数据库中创建表。数据库test存在,我得到错误No database selected。我相信,我使用的代码$select_db = mysql_select_db($database);错误:未在php中选择数据库

这里是代码选择的数据库:

$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"; 
}*/ 

?> 

回答

2
$connection = mysqli_connect($host_name,$user_name,$password); 

VS

$select_db = mysql_select_db($database); 

看起来非常接近:)查找这使得所有区别。

一旦你发现了什么问题,再次访问mysqli_connect文档看你怎么可以把它也提供数据库名。用1块石头杀死2只鸟。

0

您在混合mysqlmysqli扩展名。 mysql已弃用。仅使用mysqliPDO

// 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); 
-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; 
      } 
     } 
    } 
?> 

你可以连接到数据库并运行querys这样的:

<?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"); 
?> 

但是你啊从未真正连接到你的数据库。