PHP: Database not selected
I'm failing to understand why the function to connect to the database is not working, I have triple checked if there are any mistakes in the variables.
Using mysql_error function on class.php at line 12 I get the following 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 = "SELE开发者_运维百科CT * 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>
You're using $this->db
but never setting it. Try this:
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());
}
You are failing to set $this->db
.
First of all
mysql_select_db($this->db, $this->link) or die (mysql_error());
should be:
mysql_select_db($db, $this->link) or die (mysql_error());
and
$res = mysql_query($sql);
should be
$res = mysql_query($sql, $this->link);
精彩评论