2011-08-23 89 views
3

我不明白为什么连接到数据库的函数不工作,如果变量中有任何错误,我有三重检查。PHP:没有选择数据库

在第12行上class.php使用mysql_error功能,我得到以下错误:

No database selected 

class.php

<?php 

class blog { 
    private $host; 
    private $username; 
    private $password; 
    private $db; 
    private $link; 

    public function __construct($host, $username, $password, $db){ 
    $this->link = mysql_connect($host, $username, $password, $db); 
    mysql_select_db($this->db, $this->link) or die (mysql_error()); 

    } 

    function get_content(){ 
    $sql = "SELECT * FROM content"; 
    $res = mysql_query($sql); 
    while($row = mysql_fetch_assoc($res)){ 
     echo '<h1>'.$row['title'].'</h1>'; 
     echo '<p>'.$row['body'].'</p>'; 
     } 
    } 
}// End of Class 
?> 

的index.php

<?php include 'includes/class.php' ?> 
<?php 


//Setup Connection 
$obj = new blog('localhost', 'root', '', 'blog'); 

//Connect to DB 

?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<link rel="stylesheet" type="text/css" href="css/style.css" mce_href="styles1.css"> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Mi Blog</title> 
</head> 

<body> 

<div id="page-wrap"> 
    <?php $obj->get_content() ?> 
</div> 


</body> 
</html> 

回答

10

你使用$this->db但从未设置它。试试这个:

public function __construct($host, $username, $password, $db){ 
    $this->db = $db; 
    $this->link = mysql_connect($host, $username, $password, $db); 
    mysql_select_db($this->db, $this->link) or die (mysql_error()); 
} 
+0

大,非常感谢! –

4

所有

mysql_select_db($this->db, $this->link) or die (mysql_error()); 

首先应该是:

mysql_select_db($db, $this->link) or die (mysql_error()); 

$res = mysql_query($sql); 

应该

$res = mysql_query($sql, $this->link);