1

我有类称为数据库这里的语法

<?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 文件有什么问题?

谢谢你。

4

1 回答 1

0

告诉mysql使用哪个资源

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

mysql_* 也已被弃用,在您进一步考虑切换到 mysqli_* 或 PDO 之前

于 2013-08-04T13:35:11.063 回答