Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notice: Undefined variable: conn

Tags:

php

mysqli

When I do my DB connection like this:

$conn = new MySQLi(RUBYDBUSER, RUBYDBNAME, RUBYDBPASS, RUBYDBDATA);
if($conn->errno) {
    throw new Exception($conn->connect_error, $conn->connect_errno);
}

and I want to run a prepared statement like this:

public function getSitename() {
            $stmt = $conn->prepare("SELECT value FROM cms_options WHERE title = 'sitename' ");
            $db->stmt_init();
            $stmt->execute();
            $stmt->bind_result($sitename);
            if($stmt->num_rows > 0) {
                while ($stmt->fetch) {
                    return $sitename;
                }
            }
        }

I get this error:

Notice: Undefined variable: conn in C:\xampp\htdocs\ruby\app\includes\classes\class.core.php on line 26

The query is in class.core.php and the connection in global.php. The Class.core is included like this:

(global.php)

foreach(glob(RUBY_BASE . '/app/includes/classes/class.*.php') as $class){
    include_once($class);
}

Any answers? `

like image 642
LisaW Avatar asked May 16 '14 16:05

LisaW


1 Answers

The variable $conn is not in scope for your class methods. You need do one of the following :

A.) pass the $conn variable into the method you want to call.

 public function getSitename($conn) {
        $stmt = $conn->prepare("SELECT value FROM cms_options WHERE title = 'sitename' ");
        $db->stmt_init();
         //and so on...
}

B.) Establish the connection inside each method (not good choice because you're not reusing an established connection)

C.) Make the connection variable global with a static definition. Could be set in the constructor of the class for example:

   public function __construct($conn) {
       if(empty(static::$conn) {
           static::$conn = $conn;
       }
   }

   public function getSitename() {
       $stmt = static::$conn->prepare("SELECT value FROM cms_options WHERE title = 'sitename' ");
        //... and so on

There are many other variations like these, but they are the general approaches

like image 57
Ray Avatar answered Sep 19 '22 02:09

Ray