使用php mysqli连接数据库

时间:2014-12-31 21:49:08

标签: 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";

     }

   }



 }

?>

如果我想在类中创建一个插入函数,我会收到错误,我在非对象上调用查询。

如何在insert函数中直接调用$ mysqli对象,而不将其作为任何函数或构造函数中的参数传递。

1 个答案:

答案 0 :(得分:2)

我会在构造函数中加载数据库连接,这样你就可以使它成为该类的成员。

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