错误没有数据库选择PHP

时间:2013-08-04 11:28:49

标签: php mysql

我在这里使用Called Database这个语法

<?php
class Database
{
 var $conn = null;
 var $config = array(
    'username' => 'root',
    'password' => '',
    'hostname' => 'localhost',
    'database' => '<dbname here>'
 );

 function __construct() {
    $this->connect();
    echo 'constructor database';
}

function connect() {
    if (is_null($this->conn)) {
        $db = $this->config;
        $this->conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
        if(!$this->conn) {
            die("Cannot connect to database server"); 
        }
        if(!mysql_select_db($db['database'])) {
            die("Cannot select database");
        }
    }
    return $this->conn;
}

}

我将这个数据库文件包含在另一个php类中,让我们说它是authenticate.php

 include $_SERVER['DOCUMENT_ROOT'].'/<project_name>/configuration/database.php';

该课程是:

class authenticate {

public function __construct() {
    $db = new Database();
    $db->connect();
}

public function auth($username, $password) {
    $password = $this->HASH($username, $password);
    $query = "SELECT username, password FROM mt_user WHERE username = '$username' AND password='$password' LIMIT 1";
    $row = mysql_query($query) or die(mysql_error());
    $result = mysql_num_rows($row);
    if ($result != 1) {
        $status_login = "FALSE";
    } else
    if ($result == 1) {
        $status_login = "TRUE";
    }
    mysql_close();
    return $status_login;
}

public function getSalt($username) {
    $query = "SELECT salt FROM mt_user WHERE username = '$username'";
    $result = mysql_query($query);
    $salt = array();
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $salt = $row['salt'];
    }
    mysql_close();
    return reset($salt);
}

public function HASH($username,$password){
    $salt = $this->getSalt($username);
    $output = sha1($salt.$password);
    return $output;
}

}

?>

我将该函数调用到一个名为login.php的视图,但它在authenticate.php上抛出了“无法选择数据库”或无法连接到数据库的错误。

这个authenticate或database.php文件出了什么问题?

谢谢。

1 个答案:

答案 0 :(得分:0)

告诉mysql使用哪个资源

    if(!mysql_select_db($db['database'],$this->conn)) {
        die("Cannot select database");

也不推荐使用mysql_ *,在你进一步考虑切换到mysqli_ *或PDO之前