1

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.

3
  • 1
    Lose the @. You should not be suppressing errors that may arise. Commented Dec 31, 2014 at 21:50
  • 1
    Why don't you want to pass it through the constructor? Commented Dec 31, 2014 at 21:52
  • Also, why are there so many blank lines in the PHP file you pasted here? Commented Dec 31, 2014 at 21:56

1 Answer 1

2

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";
            }
        }
    }
?>
Sign up to request clarification or add additional context in comments.

1 Comment

TO rocket hazmat but i dnt want to load my connection file in constructor since i want to make a resuable script with maintaining the standard of oops concept.....i want a technique where i can directly call my connection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.