3

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 = "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>

3 Answers 3

10

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());
}
Sign up to request clarification or add additional context in comments.

Comments

6

You are failing to set $this->db.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.