[SOLVED]
I have solved it by calling database connection from dbfunction.php
instead of creating an object of creating object of dbconnect.php
. like this.
function __construct() {
require_once('database/config.php');
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
}
I am trying to insert data to database using mysqli. But it always shows me error
Notice: Undefined variable: conn in D:\xampp\htdocs\fokrulcart\class\dbfunction.php on line 33 Fatal error: Uncaught Error: Call to a member function query() on null in D:\xampp\htdocs\fokrulcart\class\dbfunction.php:33 Stack trace: #0 D:\xampp\htdocs\fokrulcart\reg.php(11): dbFunction->reg('re ay', 'aer yt', 'aetu') #1 {main} thrown in D:\xampp\htdocs\fokrulcart\class\dbfunction.php on line 33
Here is my connection:
<?php
class dbConnect {
function __construct() {
require_once('config.php');
$conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(!$conn)
{
die ("Cannot connect to the database");
}
else{
echo "Connected";
return $conn;
}
}
}
?>
Here is my page from where I am sending data to dbfunction.php
page.
<?php
include 'include/header.php';
include 'class/dbfunction.php';
$funObj = new dbFunction();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$f = $_POST['firstname'];
$l = $_POST['lastname'];
$e = $_POST['email'];
//echo $f. $l.$e;
$r = $funObj->reg($f,$l,$e);
}
?>
And this is my dbfunction.php
page. Error shows for this page.
<?php
require_once 'database/dbConnect.php';
class dbFunction {
public $db;
public $conn;
function __construct() {
$conn = new dbConnect();
}
public function reg($l, $f, $e){
$sql = "INSERT INTO reg (f, l, e)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) { //error shows here.
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}