2016-02-11 44 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

相關問題