This question already has an answer here:
i want to access $conn in class mention in bellow.
conn_file.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if($conn->connect_error)
{
die("Connection Failed :".$conn->connect_error);
}
?>
class.function.php
<?php
include_once 'conn_file.php';
class all_function
{
public function something()
{
$data = $conn->real_escape_string("data");
return $data;
}
}
?>
The above gives me the following error: Notice: Undefined variable: conn in class.function.php on line 7
Fatal error: Call to a member function real_escape_string() on a non-object in class.function.php on line 7
</div>
I suggest you to use class
for connection. Example:
In conn_file.php
class DbConfig{
public static $servername = "localhost";
public static $username = "root";
public static $password = "";
public static function getCon(){
$conn = new mysqli(self::$servername, self::$username, self::$password);
if($conn->connect_error){
die("Connection Failed :".$conn->connect_error);
}
return $conn;
}
}
In class.function.php
include_once 'conn_file.php';
class all_function
{
public function something()
{
$conn = DbConfig::getCon();
$data = $conn->real_escape_string("data");
return $data;
}
}