Reputation: 41
This is my connection file
<?php
$mysqli= @new mysqli("localhost","root","","ngo_sharda");
if($mysqli->connect_errno)
{
printf ("connection failed %s \n",mysqli_connect_error());
}
?>
And this is my class file...
<?php
include('../connection.php');
class operation
{
private $title;
/*
function __construct()
{
$this->title=$m;
}
*/
function setvalues()
{
$this->title=$m;
}
function insert()
{
$q="insert into menus(title,link) values('kumar','great')";
//$result=mysqli_query($mysqli,$q);
$result= $mysqli->query($q);
if($result==1)
{
echo "inserted";
}
else
{
echo "not inserted";
}
}
}
?>
if i am trying to create a insert function inside the class i am getting error that i am calling query on a non object.
how can i call $mysqli object directly inside this class in insert function without passing it as an argument in any function or in constructor.
Upvotes: 1
Views: 666
Reputation: 227310
I would load the database connection inside the constructor so you can make it a member of the class.
<?php
class operation{
private $title;
private $mysqli;
function __construct(){
// include basically copies & pastes the file
include('../connection.php');
// $mysqli exists inside this function, let's make it
// available in the rest of the class
$this->mysqli = $mysqli;
//$this->title = $m;
}
function setvalues(){
$this->title = $m;
}
function insert(){
$q = "insert into menus(title,link) values('kumar','great')";
// Now we can access `$this->mysqli` and everything should work
$result = $this->mysqli->query($q);
if($result==1){
echo "inserted";
}
else{
echo "not inserted";
}
}
}
?>
Upvotes: 2