无法访问其他文件中的mysqli连接对象?

时间:2017-11-09 06:42:41

标签: php mysql mysqli

dbConnection.php

<?php
include_once('config.php');
$dbConnection = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
  if($dbConnection->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
  }
  mysqli_set_charset($dbConnection, 'utf8');
?>

news.php

<?php
  require_once('dbConnection.php');
  function getNews($request){
      $sql = "select * from news";
      if (!$result = $dbConnection->query($sql)) {
          die('There was an error running the query [' . $dbConnection->error . ']');
      }

      $news = array();
      while ($row = $result->fetch_assoc() ){
        $news[]=$row;
      }

      $result->free();
      $dbConnection->close();
      return $news;
  }

  $latestNews = getNews($_REQUEST);
  echo json_encode($latestNews);
 ?>

我收到错误未定义的变量:xx行上的dbConnection。 有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

您收到此错误是因为您尝试在函数内访问此变量。

您应该将变量作为参数传递,如下所示:

function getNews($request, $dbConnection) {...}
$latestNews = getNews($_REQUEST, $dbConnection);

或使用global

function getNews($request)
{
    global $dbConnection;
    ...
}

答案 1 :(得分:0)

您尝试在函数外声明的函数中使用变量,必须使用全局

<?php
  require_once('dbConnection.php');
  function getNews($request){
      global $dbConnection;
      $sql = "select * from news";
      if (!$result = $dbConnection->query($sql)) {
          die('There was an error running the query [' . $dbConnection->error . ']');
      }

      $news = array();
      while ($row = $result->fetch_assoc() ){
        $news[]=$row;
      }

     $result->free();
     $dbConnection->close();
     return $news;
 }

 $latestNews = getNews($_REQUEST);
 echo json_encode($latestNews);

&GT;

答案 2 :(得分:-1)

只需将require_once(dbConnection.php)放在函数内部,使其成为函数的本地函数。像这样 -

<?php 
function getNews($request){
  // put it here
  require_once('dbConnection.php');
  $sql = "select * from news";
  if (!$result = $dbConnection->query($sql)) {
      die('There was an error running the query [' . $dbConnection->error . ']');
  }

  $news = array();
  while ($row = $result->fetch_assoc() ){
       $news[]=$row;
  }

  $result->free();
  $dbConnection->close();
  return $news;
  }

  $latestNews = getNews($_REQUEST);
  echo json_encode($latestNews);

&GT;

它会起作用。