简体   繁体   中英

connecting to database using php mysqli

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.

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";
            }
        }
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM