繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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