注意:未定义变量:conn [英] Notice: Undefined variable: conn

查看:244
本文介绍了注意:未定义变量:conn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我像这样进行数据库连接时:

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;
                }
            }
        }

我收到此错误:

注意:未定义的变量:第26行的C:\ xampp \ htdocs \ ruby​​ \ app \ includes \ classes \ class.core.php中的conn

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

查询在class.core.php中,连接在global.php中.这样包含了Class.core:

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

(global.php)

(global.php)

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

有答案吗? `

推荐答案

变量$conn不在您的类方法的范围内.您需要执行以下操作之一:

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

A.)将$ conn变量传递到您要调用的方法中.

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.)在每种方法中建立连接(这不是一个好选择,因为您不会重用已建立的连接)

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

C.)使用静态定义使连接变量成为全局变量.可以在类的构造函数中进行设置,例如:

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

这篇关于注意:未定义变量:conn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆