Jump to content

mysql_real_escape_string() expects parameter 2 to be resource


waynew

Recommended Posts

Hey guys. I'm creating my own custom db class and I've come across a slight problem. Firstly, let me show you the class.

 

<?php

class Database{

	var $password = "";
	var $username = "root";
	var $hostname = "localhost:8080";
	var $database = "";
	var $last_result = NULL;
	var $con;

	function connect(){
		$connection = mysql_connect($this->hostname,$this->username,$this->password) or die(mysql_error());			
		$this->con = $connection;
		if($this->database != ""){
			mysql_query("USE ".$this->database) or die(mysql_error());
		}
	}

	function query($query){
		$result = mysql_query($query,$this->con) or die(mysql_error());
		$this->last_result = $result;
		return $result;
	}

	function set_database($db){
		$this->query("USE $db");
		$this->database = $db;
	}

	function clean($string){
		if(get_magic_quotes_gpc() == 1){
			$string = stripslashes($string);
		}
		$string = mysql_real_escape_string($string,$this->con);
		return $string;
	}

	function free($result){
		mysql_free_result($result);
	}
}
?>

Now I keep getting this whenever I use the clean function error:

 

mysql_real_escape_string() expects parameter 2 to be resource, null given

 

I know for a fact that I've successfully established a connection as the function query works fine.

 

What could be the problem?

 

 

Here it is,

 

$user = new User();
$db = new Database();
$db->connect();
$db->set_database("classtest");
$user->register_user("Wayne","Tester","Email","Name");

 

The class user, which uses the clean function of the DB class goes like:

 

<?php

class User{

var $db;

function User(){
	$database = new Database();
	$this->db = $database;
}

function register_user($username,$password,$email,$name){
	$username = $this->db->clean($username);
	$password = $this->db->clean($password);
	$email = $this->db->clean($email);
	$name = $this->db->clean($name);
}
}

?>

 

I'm expecting something stupid. I've had long days these past few weeks.

You're instantiating a new Database in User, instead of passing in the existing one, and the new one isn't connected.  Also, why in the world are you using PHP4 OOP syntax?  It's really not good to be using any more.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.