使用 PHP Mysqli 连接到数据库


connecting to database using php mysqli

这是我的连接文件

<?php
$mysqli= @new mysqli("localhost","root","","ngo_sharda");
if($mysqli->connect_errno)
{
    printf ("connection failed %s 'n",mysqli_connect_error());

} 
?>

这是我的班级文件...

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

 }
?>

如果我尝试在类中创建插入函数,则会收到错误,指出我正在对非对象调用查询。

如何在插入函数中直接在此类中调用$mysqli对象,而无需将其作为任何函数或构造函数中的参数传递。

我会在

构造函数加载数据库连接,以便您可以使其成为类的成员。

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