Re: Problem with storing queries in a function file

From: Date: Sat, 12 Jun 2004 15:39:33 +0000
Subject: Re: Problem with storing queries in a function file
References: 1  Groups: php.pear.general 
Request: Send a blank email to pear-general+get-13117@lists.php.net to get a copy of this message
Hi George! "George Pitcher" <george.pitcher@ingenta.com> wrote in message news:AMEPJAJDOFCDLPGFDOIFMEACECAA.george.pitcher@ingenta.com... > Hi, > > I'm porting an existing (working) site to PEAR:DB and in my functions file, > included near the beginning of each script, I have around 30 queries stored > as functions. > > For example, in my site, we store lots of courses and the relevant data > associated with them. Lecturers names are stored in a separate table and are > referenced by an id stored in the course table. > > So when I want to include the name of the lecturer in the web page I simpley > store the id in a variable and pass it to a function like: > > $lect_name = lecturer($lect_id); > > The function looks like: > > 117 function lect($lect_id){ > 118 $sql = "Select * FROM lecturers WHERE (id=$lect_id)"; If you're working with MySQL you don't need the braces around your WHERE condition: "Select * FROM lecturers WHERE id = $lect_id" > 119 $cur = $db->query( $sql ); > 120 while($row = $cur->fetchRow()){ > 121 $lect_name = ltrim(stripslashes($row[1].' '.$row[3].' '.$row[2])); > 122 } > 123 return $lect_name; > 124 } > file://Line numbers are displayed for reference > > I'm getting an error "Call to a member function on a non-object in > c:\inetpub\wwwroot\smartPT\includes\functions.php on line 119" > > The beginning of my script is: > > <?php > include("includes/auth.php"); // checks for an authenticated cookie > require 'Smarty.class.php'; // I'm using Smarty templating > $smarty = new Smarty; // > include("includes/dbinfo.php");// See below > > dbinfo is: > > <?php > $dbhost = 'localhost'; > $dbuser = 'root'; > $dbpass = ''; > $dbname = 'pt_demo'; > require_once( 'DB.php' ); > $db = DB::connect( "mysql://$dbuser:$dbpass@$dbhost/$dbname" ); You should assign $db as a reference: $db =& DB::connect("mysql://$dbuser:$dbpass@$dbhost/$dbname"); > $smarty->assign('access', $access); > include('c:\inetpub\wwwroot\smartPT\includes\functions.php'); > ?> > > Now, the way I see it, everything is being loaded in the correct order, so > I'm a bit stumped as to why my function fails. > > Any ideas? In your functions you are using $db but it's not declared. You must either pass $db to every function as a parameter or make it global in every function (what I would recommend): function lect($lect_id) { global $db; // ... rest of your code follows } This should solve your problem. Regards, Torsten Roehr

« previous php.pear.general (#13117) next »