0

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);
 ?>

I am getting error Undefined variable: dbConnection on line xx. Can anybody please help me to fix the issue?

Hitendra
  • 3,218
  • 7
  • 45
  • 74
  • That's not because it's on another file, that's because it's inside a function. You should pass the `$dbConnection` as a parameter or use `global $dbConnection`. – HTMHell Nov 09 '17 at 06:48

3 Answers3

1

You are getting this error because you are trying to access this variable inside a function.

You should pass the variable as a parameter, like this:

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

Or use global:

function getNews($request)
{
    global $dbConnection;
    ...
}
HTMHell
  • 5,761
  • 5
  • 37
  • 79
0

You're trying to use a variable within function declared outside of function, you must use global

<?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);

?>

Aniket Singh
  • 2,464
  • 1
  • 21
  • 32
-1

Just put the require_once(dbConnection.php) inside the function to make it local to the function. Like this -

<?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);

?>

And it will work.

MukeshSri369
  • 1
  • 1
  • 1