将mysql连接作为参数传递时出错

时间:2016-06-09 16:19:09

标签: php mysql api

我正在尝试使用PHP和mysql构建基本API,并且根据url路径,使用不同的数据库表,因此需要进行连接。但我一直收到这个错误:

  

致命错误:在非对象上调用成员函数prepare()   在......第6行

dashboard.class.php:

class dashboard {
    public function getData($conn) {
        // Get latest status
        $stmt = $conn->prepare("SELECT status FROM status_archive ORDER BY datetime DESC LIMIT 1 ");
        $stmt->execute(); //line 6
        $stmt->bind_result($status);
        $stmt->fetch();
        ($status == '1' ? $status = 'up' : $status = 'down');
        $stmt->close();
        return $status;
    }
}

创建数据库连接的函数:

function db_connection($type) {
   $db = $type.'_db';
   syslog(LOG_INFO, 'DB: '.$db);
   // Check to see if a development or production server is being used
   if (strpos(getenv('SERVER_SOFTWARE'), 'Development') === false) {
      $conn = mysqli_connect(null,
                              getenv('PRODUCTION_DB_USERNAME'),
                              getenv('PRODUCTION_DB_PASSWORD'),
                              $db,
                              null,
                              getenv('PRODUCTION_CLOUD_SQL_INSTANCE'));
   } else {
      $conn = mysqli_connect(getenv('DEVELOPMENT_DB_HOST'), 
                              getenv('DEVELOPMENT_DB_USERNAME'),
                              getenv('DEVELOPMENT_DB_PASSWORD'),
                              $db);
   }
   // Check if successful connection to database
   if ($conn->connect_error) {
      die("Could not connect to database: $conn->connect_error " .
         "[$conn->connect_errno]");
   }

   return $conn;
}

这是启动所有内容的文件末尾的代码:

$path_array = explode("/", parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
$conn = db_connection($path_array[3]);
include 'classes/dashboard.class.php';
$dashboard = new dashboard;
$results = $dashboard->getData($conn);
echo json_encode($results, JSON_PRETTY_PRINT);

2 个答案:

答案 0 :(得分:0)

mysqli_connect可以返回假值 您应该使用OOP样式(new mysqli)或检查$conn

$conn = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

if (!$conn) {
    die('Connection error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

php.net - 请参阅“程序样式”示例。

答案 1 :(得分:0)

原来这是由于范围可变。

我最终使用PHP $ GLOBALS来使其工作。