XCode2015 XCode2015 - 4 months ago 8
MySQL Question

Require_once config.php not working with function php

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 !

Answer

Please try this:

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