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.
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:
There are many other variations like these, but they are the general approaches
This due to variable scope, $conn is defined outside the function, so or you pass it as parameter, or you set it as global, or you use an anonymous function.
If $conn is initialized in the same file or in any other file and is included in the file which defines the
getSitename()
function, then you can mark the$conn
variable as gloabl inside the function and it will work.