-1

I have a problem with my code, hope everyone can help me.

This is my config.php

$host = "localhost";
$db_user = "root";
$db_pass = "vertrigo";
$db_name = "DBname";
$mysqli = new mysqli($host, $db_user , $db_pass, $db_name);
mysqli_set_charset($mysqli, 'UTF8');
if ($mysqli->connect_errno) {
  echo "Errno: " . $mysqli->connect_errno . "<br />";
  echo "Error: " . $mysqli->connect_error . "\n";
  exit;
}

I require it into index.php with function lib like

require_once("config.php");
require("lib/select.php");

This is my select lib

function SelectAdmin()
{
    $sql = "SELECT * from admin order by id ASC";
    $result=$mysqli->query($sql);
    return $result; 
}

Then, i'm call it in index.php

while ($rows = SelectAdmin()->fetch_assoc()) 
{ 
    echo $rows['Fullname'];
}

But it show error

Undefined variable: mysqli in .... \lib\select.php on line 8

Please help me. Thank you !

XCode2015
  • 193
  • 1
  • 1
  • 10

3 Answers3

0

This is a classic scope problem.

You declared $mysqli in the "main" scope, let's call it "level 0", and now you want to access it in SelectAdmin(). But there is no $mysqli variable defined in that method, because within that method your are at "level 1".

You can tell SelectAdmin() to use the variable at level 0 by marking that variable as global: global $mysqli.

Or even better, you can define a Connect() method that makes the connection every time you need it.

So in SelectAdmin() you will have to call $mysqli = Connect() and that should work in every method where you need a connection.

Vladimir Nul
  • 2,174
  • 1
  • 15
  • 26
0

pass the $mysqli to the function so that it can get access to the $mysqli varible

function SelectAdmin($mysqli) {
    $sql = "SELECT * from admin order by id ASC";
    $result=$mysqli->query($sql);
    return $result; 
}
Arun Kumaresh
  • 5,734
  • 5
  • 28
  • 45
-2

Please try this:

function SelectAdmin() {
    global $mysqli;//You need this !
    $sql = "SELECT * from admin order by id ASC";
    $result=$mysqli->query($sql);
    return $result; 
}
Ismail RBOUH
  • 9,218
  • 1
  • 18
  • 33