Why its causing error in function?

Hi,

I have a simple function in which I am running a sql query and return the data:

$stmt = $conn->prepare("SELECT * FROM categories WHERE catg_pid = '0' AND catg_status = '1' ORDER BY catg_name ASC");
	$stmt->execute(); $num_rows = $stmt->fetchColumn();
	
	if (!empty($num_rows))
	{
		$retdata = "";
		
		while($catgs = $stmt->fetch(PDO::FETCH_OBJ))
		{
			$retdata .= "<option value=\\"" . $catgs->catg_id . "\\">" . $catgs->catg_name . "</option>\
";
		}
	}
	
	return ($retdata);

But instead of returning data its giving me this error:


Fatal error</b>: Call to a member function prepare() on a non-object in <b>functions.php</b> on line <b>26

What is wrong with this ?

Thanks.

Hi Tapan,

I think probably what’s happening is that you’re creating your DB connection outside of the function, and then trying to call it inside of the function without passing it in as an argument.

Hi,

Yes I had a config.php file in which I had code like this:

try 
{
	$conn = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_pass);
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    
} 
catch(PDOException $db_error) 
{
	die ("WARNING: CONNECTION FAILED.");
}

And I would write sql queries in all other pages which was working.

But in order to make it work for functions I had to remove it from config and I had to put this code above every query I am doing in every page:

$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);

Earlier was fine but this is also okay. I have ot put this $conn above every query in order for it to work now whether in functions or in normal code. Am i doing it correctly ?

Thanks.

You could do global $conn for it to work inside the function. Or create a class that inherits the DB function and then write all your functions as part of that class.


class db_functions {
 var $conn = null;

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

public function simple_test() {
 return  $this->$conn->prepare("SELECT * FROM categories WHERE catg_pid = '0' AND catg_status = '1' ORDER BY catg_name ASC");
}

}

Hi,

How to create global conn ?

Thanks.

Just put the global keyword in front of the variable.

global $conn;