SOLVED - Use my database class within another class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Griven
Forum Contributor
Posts: 165
Joined: Sat May 09, 2009 8:23 pm

SOLVED - Use my database class within another class

Post by Griven »

Hey all. I've Googled all around, and pulled my hair out for a few days now, so I figured I'd turn to the boards.

I've got a main page called index.php, which calls up my classes. From there, I've got two classes. My Database class, which creates a MySQLi connection, and my Security class, which checks the user's Windows username against a database (this is an intranet site, by the way--no passwords).

I would like to be able to use my Database object within my Security class, to query the database.

Below are some code snippets:

index.php

Code: Select all

<?php
 
######## Connect to the database and create a new DB object
require_once('inc/classes/db.class.php');
$db = new db;
################
 
######## Create a new security object, and check the user's security rights
require_once('inc/classes/security.class.php');
$sec = new Security;
 
$fullusername = $_SERVER['AUTH_USER'];  
$usernamearray = explode('\\', $fullusername);
$domain = $usernamearray[0];
$winlogon = $usernamearray[1];
 
$sec->checkuser($domain,$winlogon);
security.class.php

Code: Select all

<?php
class Security{
    
    function checkuser($domain, $winlogon){
        if ($userrecord = $this->db->query("SELECT * FROM users WHERE user_domain = '$domain' AND user_winlogon = '$winlogon' LIMIT 1")){
        //Do stuff
    } 
    
}
That particular code throws an error saying "Call to a member function query() on a non-object". This is expected, as I haven't defined the $db object within this class. If I change $this->db->query to just $db->query, it says that it's an undefined variable.

How can I use my Database class, an object of which has already been created on index.php, within my Security class?
Last edited by Griven on Wed Oct 21, 2009 8:48 pm, edited 1 time in total.
Griven
Forum Contributor
Posts: 165
Joined: Sat May 09, 2009 8:23 pm

Re: Use my database class within another class

Post by Griven »

Nevermind, I got it.

SOLUTION:

Code: Select all

<?php
class Security extends db{
    
    function checkuser($domain, $winlogon){
        if ($userrecord = $this->query("SELECT * FROM users WHERE user_domain = '$domain' AND user_winlogon = '$winlogon' LIMIT 1")){
 //Do stuff
} 
Post Reply