Jump to content

mysqli oop in class help


The14thGOD

Recommended Posts

I'm new to the whole OOP thing so please excuse the sloppiness/potential bad code. I've gone through a lot of tutorials and a cookbook I have and have what I thought was a good understanding of it (as much as I can get from reading about it at least). Now I'm trying to put it into practice with a side project.

 

Basically I'm trying to check if a user already exists, here's the db class: (I'm going to assume this is the wrong way to do this so any help (books/links) greatly appreciated)

<?php
class database{
	private $_db_host = DB_HOST;
	private $_db_name = DB_NAME;
	private $_db_user = DB_USER;
	private $_db_pass = DB_PASS;
	private $_db_link = '';

	public function __construct(){
		/*
		 *Create a mysqli connection object within the db object
		 *To reference the mysqli functions you have to call:
		 $this->_db_link as if it was $mysqli (outside of a class)
		 */
		$this->_db_link = new mysqli($this->_db_host,$this->_db_user,$this->_db_pass,$this->_db_name);
		if(mysqli_connect_errno()){
			die('Could not connect: '.mysqli_connect_error());
		}
	}
	public function __destruct(){
		$this->_db_link->close();
	}

	//this function works, I get the full list
	public function list_types(){
		if($results = $this->_db_link->query('SELECT type FROM types ORDER BY type ASC')){
			while($row = $results->fetch_assoc()){
				echo $row['type'].'<br />';
			}				
			//free result set
			$results->close();
		}
	}
}

 

Here's my incompelte user class:

<?php
class user{
	private $username = '';

	public function check_user_exists($user){
		if($stmt = $db->_db_link->prepare("SELECT username FROM users WHERE username='?'")){
			$stmt->bind_param('s',$username);

			$username = $user;				
			$stmt->execute();
			$stmt->num_rows == 0 ? $chk = true : $chk = false;
		}
		return $chk;
	}

}

 

Code that calls user class (db class is called in the configuration, I pretty much always need a db connection, but again, I'm sure this is bad)

<?php
$db = new database(); //called in a configuration file
$user = new user();
	if($user->check_user_exists($username)){
		echo 'user does not exist';
		exit(0);
	}

 

The error:

Fatal error: Call to a member function prepare() on a non-object

 

which is $db->_db_link->prepare()

but $db->_db_link->query() will work...

 

It's weird to me that the db connection is inside another object, is this right?

 

Any and all help would be greatly appreciated (google is not helping me find a mysqli prepared oop in class example). No one I work with/know has a good understanding of what OOP is so I'm stuck trying to learn it on my own.

 

Thanks,

Justin

 

edit #1: at first i thought it was the fact $_db_link = private, but i changed it to public and it had no effect

Link to comment
Share on other sites

First, there's not a lot of point wrapping your Mysqli object within another object.  It's already an object, and you're not adding any real functionality to it.

 

Second, objects contain references to other objects all the time.  That's where the true power of OOP lies.  Composition (objects referencing or containing one another) is generally preferable to inheritance.  That's not to say inheritance is bad, it's just that unless you're defining a family of classes, composition is the way to go.

 

What you need to do is create your Mysqli object, then pass it into your User object's constructor, like so:

 

class User
{
   private $db;

   public function __construct($db)
   {
      $this->db = $db;
   }

   // rest of class
}

$db = new mysqli($db_host, $db_user, $db_pass, $db_name);

$user = new User($db);  // there are better/more advanced ways to do this, but stick with this for now

Link to comment
Share on other sites

sweet, I'll try this when I get home in a bit (on my way out). Would you mind hooking me up with a link or a proper Google query for the better/advanced way? I don't mind researching on my own, I just have a hard time formulating the right query. I'll let you know how this goes after I fix it, thx =)

Link to comment
Share on other sites

Nope, I just have the O'Reilly cookbook that has a chapter about OOP. I found Zandstra's book on Amazon though, in que, thx.

Also just switched all the code and it works. Makes a lot more sense once I trashed that db class. Was stuck trying to figure out how the classes all talked to each other to use the dblink. But yea, passing the db variable every time seems bad ^_^

Link to comment
Share on other sites

Yeah, a chapter on OOP really won't cut it.  It will teach you just enough to get really confused about all of it.

 

For $db, you have two general choices -

 

1. Hard code it into the object(s) that need to use it.  Bad idea, for obvious reasons.

 

2. Inject it into the object(s) that need to use it.  Much better, as you can change database implementations on the fly.  This is what you're doing with the constructor.

Link to comment
Share on other sites

Yea, its definitely confusing. I've read a good amount of tutorials and done basic OOP stuff (nothing with DB though). I feel I have a decent understanding but obviously not perfect. Putting it to use will change that significantly though. Thanks again for your help =)

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.