0

Here is mycode dbclass.php i am new for oops concept,

<?php
   class Database {
      private $link;
      private $hostname, $username, $password, $dbname;
      public function __construct( $hostname, $username, $password, $dbname ) {
         $this->link=mysql_connect($this->hostname,$this->username,$this->password) or die("Mysql Connection error!!");
         mysql_select_db($this->dbname,$this->link) or die("error:".mysql_error());
         return true;
      }
      public function query( $query ) {
         $result = mysql_query( $query );
         if ( !$result ) {
            die('Invalid query: ' . mysql_error());
         }
         return $result;
      }
      public function __destruct() {            
        mysql_close($this->link) or die("Error:".mysql_error());
      }
   }    
?>
<?php 
   include("dbclass.php");
   $db = new Database("localhost", "root", "password", "test");
   $result = $db->query("select * from messages");
   while ( $row = mysql_fetch_array( $result ) ) {
      echo $row['id'];
   }
?>

if i run this code it showing database not connected. I don't know why?

5
  • 2
    Forget about mysql_* functions. Start using PDO instead Commented Oct 10, 2013 at 8:56
  • or mysqli_ methods (easier to understand as beginner it's allmost the same as the mysql) Commented Oct 10, 2013 at 8:56
  • No password was not empty im sure about that, its a correct password Commented Oct 10, 2013 at 8:59
  • Agree with @DaveJust, or at least use mysqli it will be easy for you to migrate. Commented Oct 10, 2013 at 9:02
  • Sure, I will definitely use PDO or mysqli. Commented Oct 10, 2013 at 9:03

1 Answer 1

2

The problem is here :

$this->link=mysql_connect($this->hostname,$this->username,$this->password)

You are not assigning the argument in function to your variables of class. Hence do this

$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;

and then give:

 $this->link=mysql_connect($this->hostname,$this->username,$this->password);
Sign up to request clarification or add additional context in comments.

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.