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? `
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With