Jump to content

classes and mysql connections


littlened

Recommended Posts

Usually when I use PHP I create an include file which contains the relevant username,password,host for the mysql connection, and I simply include this file each time I need to make a connection to the database.

I'm trying to use classes to get data from a database and return the results, however I'm not sure how I go about assigning the username,password without having to do it manually inside each class. I've tried including an external file using include() but I get an error.

Does anyone have any ideas?
Link to comment
Share on other sites

Just include the file that has your database details in your
constructor or function that creates the connection to the database

Here is a simple database class:

[code]class DB {

    var $host = '';
    var $user = '';
    var $pass = '';
    var $dbase = '';

    // this gets called when we initiate the class
    // this is called a constructor
    // constructors have the same name as the class
    function DB()
    {
        // change this to location of you php file with you details
        include 'path/to/your/dbdetails.php';

        // setting up the class variables
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->dbase = $dbase;

        // connect to the database automatically
        $this->connect();
    }

    function connect()
    {
        $this->conn = mysql_connect($this->host, $this->user, $this->pass);

        mysql_select_db($this->dbase, $this->conn);
    }
}[/code]

When you go to connect to the database initiate the class:
[code]// connect to database.
$db = new DB;[/code]
Link to comment
Share on other sites

thats seems fair enough, but how do I then get a function within another class to use that specific database connection?

So far I've only opened a database connection from within the same class I need to use it, so I can use $this->conn, but how do I do it from inside another class?
Link to comment
Share on other sites

You'll need to include your DB class in any other classes that need it. eg;

[code]
<?php
  class foo {
    private $db;
    function __construct() {
      include 'classes/db.class.php';
      $this->db = new DB();
    }
  }
?>[/code]
Link to comment
Share on other sites

ok I've gave this a go but all I get is

mysql_query(): supplied argument is not a valid MySQL-Link resource in

here is the db class

[code]
class DB {

    var $host = 'localhost';
    var $user = 'dsfsdf';
    var $pass = 'dsfsdf';
    var $dbase = 'sdfsdfsdf';

    function DB()
    {
        $this->connect();
    }

    function connect()
    {
        $this->conn = mysql_connect($this->host, $this->user, $this->pass);
        mysql_select_db($this->dbase, $this->conn);
    }
}
[/code]

here is the class which calls the db class

[code]
class categories {

function categories() {

} // end categories function

function get_categories() {
include 'classes/cls_db.php';
      $this->dblink = new DB();

$categories = array();
$query = "SELECT Category_ID,Category_Name,Category_Display FROM Categories ORDER BY Category_Name ASC ";
      $result = mysql_query($query, $this->dblink);
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result)) {
$categories[] = $row;
}

return $categories;
} // end get_cats function

} // END CLASS
[/code]

and finally here is the code which calls the categories class.

[code]require_once('classes/cls_categories.php');

$categories = new categories;

$Action = $_REQUEST['a'];
if ($Action == '') $Action = 'list';

if ($Action == 'list') {
$categories_list = $categories->get_categories();
print_r($categories_list);
} // end action IF[/code]
Link to comment
Share on other sites

Here:
[code]include 'classes/cls_db.php';
      $this->dblink = new DB();[/code]
is wrong. The DB Class does not return a MySQL resource link, however it does hold the resource link in a variable called conn within the DB class. What you'll want to do use this when connecting to the database:
[code]nclude 'classes/cls_db.php';
      $db = new DB();[/code]
Then to get the resource link use $db->conn intead of $this->dblink
Link to comment
Share on other sites

ok so I've modified the code to this, but now I get the following errors:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/alive/public_html/clients/zund/www/manager/classes/cls_categories.php on line 16

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/alive/public_html/clients/zund/www/manager/classes/cls_categories.php on line 17

[code]
class categories {

function categories() {

} // end categories function

function get_categories() {
include 'classes/cls_db.php';
      $db = new DB();

$categories = array();
$query = "SELECT Category_ID,Category_Name,Category_Display FROM Categories ORDER BY Category_Name ASC ";
                   $result = mysql_query($query, $db->conn);
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result)) {
$categories[] = $row;
}

return $categories;
} // end get_cats function

} // END CLASS
[/code]
Link to comment
Share on other sites

If you are getting that error then it more like to be an error with your query. Change this line:
[code]$result = mysql_query($query, $db->conn); [/code]
to:
[code]$result = mysql_query($query, $db->conn) or die("Error with query:<br /><pre>{$query}</pre><br /><br >" . mysql_error());[/code]
Post the error message you get in full here.

[b]EDIT:[/b]

Oh poop! I Forgot to set up the conn variable in the db class, Add the following code:
[code]var $conn = '';[/code]
after [tt]var $dbase = '';[/tt] in the DB class.
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.