Jump to content

need guidance on using classes


CyberShot

Recommended Posts

I am trying to set up a class for my database connection. I have it working one way, this is a completely new method I am trying to learn. I have a file called MyClasses.php and in that file I did this. (I am following a not very well done tutorial)

 


class MySQLDatabase
{
private $connection;

function __construct(){
	$this->open_connection();
}
public function open_connection(){
	$this->connection = new MySQLi('localhost','MyDatabase','password','billpay') or die($mysql->error);
}
}
$database = new MySQLDatabase();

 

then in my index page where I want to begin by doing a query on the database, I did this

 

<?php include MyClasses.php ?>

$result = $database->query("SELECT * FROM names") or die($mysql->error);

 

but that gives me this error

 

Fatal error: Call to undefined method MySQLDatabase::query() in C:\wamp\www\BillPay\index.php

 

I can't figure out how to get past it.

Link to comment
Share on other sites

No, you will have to do this:

 


class MySQLDatabase
{
   private $connection;
   
   function __construct(){
      $this->open_connection();
   }
   public function open_connection(){
      $this->connection = new MySQLi('localhost','MyDatabase','password','billpay') or die($mysql->error);
   }

  public function query($query){
    return $this->connection->query($query);
  }

}

 

I'm not really sure this is the best way to be interacting with the database. You might consider downloading a decent library which already has this setup for you.

Link to comment
Share on other sites

The main reason for using mysqli inside this class is to abstract the database access layer. If you don't require that, then it is simply a case of managing the database connection effectively.

 

Should note that simply having this as it is, is hardly considered abstraction. The only use is it contains a central place for database connection settings.

 

Some simple documentation on mysqli here:

 

http://www.php.net/manual/en/mysqli.query.php

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.