2016-02-11 45 views
0
/*connection file*/ 
    function connect(){ 
      $server = "localhost"; 
      $user = "xxxx"; 
      $password = "xxxx"; 
      $db = "xxxx"; 
      $connetion = mysqli_connect($server,$user,$password,$db); 
    } 

这是我的连接文件。我使用MVC连接到数据库。mysqli_query()期望参数1为mysqli,null给出

/*function declaration and insert query*/ 
    function insert($table,$value){ 
     $fld = ""; 
     $val = ""; 
     $i = 0; 
     foreach ($value as $k => $v) { 
      if($i == 0){ 
       $fld .= $k; 
       $val .= "'" . $v ."'"; 
      } 
      else{ 
       $fld .= "," . $k; 
       $val .= ",'" .$v . "'"; 
      } 
      $i++; 
     } 
     global $conn; 
     return mysqli_query($conn,"INSERT INTO $table($fld) VALUES($val)") or die(mysqli_error($conn)); 
    } 

当我尝试向数据库中插入数据时发出警告。

请帮我解决这个警告。

+0

想看看你是如何扩展连接文件 –

+0

include_once'./connection.php';我像这样扩展了我的连接文件。 –

+0

你需要使用return语句。并将其存储在$ conn变量中, –

回答

0

您需要从函数connect返回连接对象。

function connect(){ 
     $server = "localhost"; 
     $user = "xxxx"; 
     $password = "xxxx"; 
     $db = "xxxx"; 
     $connection = mysqli_connect($server,$user,$password,$db); 
     return $connection; // return connection object 
} 
0

您需要返回$connection,这样就不会在global $connection;是不确定的:

function connect(){ 
    $server = "localhost"; 
    $user = "xxxx"; 
    $password = "xxxx"; 
    $db = "xxxx"; 
    $connection = mysqli_connect($server,$user,$password,$db); 
    return $connection; // return $connection 
} 

注意:你拼写错误$connection,不应该是$connetion

+0

'$ conn'没有在函数中定义,但'$ connection'是。 – Sean

+0

我也做了它,但它给了我警告的同样的警告:mysqli_query()期望参数1是mysqli,null给出。 –

+0

@ShahAnkit你纠正了拼写错误吗? – Panda

相关问题