2017-04-25 90 views
0

我知道必須在mysqli編碼部分mysql bt new。我無法執行這些插入查詢到數據庫。我搜查了很多,但找不到簡單的建議,或者可能是我不明白。與OOP mysqli擴展類的數據庫連接

未定義變量:mysqli的在C:\瓦帕\ WWW \上線新建文件夾\ PHP \ msqliconnect.php 32

致命錯誤:調用一個成員函數mysqli_query()在C語言的非對象: \ wamp \ www \新文件夾\ php \ msqliconnect.php在線32

任何幫助表示讚賞。

<?php 
class connection 

    { 
    public $mysqli; 

    function connect() 
     { 
     $hostname = "localhost"; 
     $username = "root"; 
     $password = ""; 
     $database = "demodatabase"; 
     $mysqli = new mysqli($hostname, $username, $password, $database); 
     /* check connection */ 
     if (mysqli_connect_errno()) 
      { 
      printf("Connect failed: %s\n", mysqli_connect_error()); 
      exit(); 
      } 

     return true; 
     } 
    } 

class Index extends connection 

    { 
    function __construct() 
     { 
     parent::connect(); 
     } 

    function insertdata($a, $b) 
     { 

     // echo $a. ' ' .$b; 
     // MySqli Insert Query 

     $status = 0; 
     $insert_row = $mysqli->mysqli_query("INSERT INTO tb_user (id, user, password, status) VALUES('','" . $a . "', '" . $b . "', '')"); 
     if ($insert_row) 
      { 
      print 'saved'; 
      } 
      else 
      { 
      die('Error : (' . $mysqli->errno . ') ' . $mysqli->error); 
      } 
     } 
    } 

?> 
+0

您的代碼容易受到[** SQL注入攻擊**](https://en.wikipedia.org/wiki/SQL_injection)的影響。你應該使用[** mysqli **](https://secure.php.net/manual/en/mysqli.prepare.php)或[** PDO **](https://secure.php.net/ manual/en/pdo.prepared-statements.php)準備帶有綁定參數的語句,如[**這篇文章**]所述(https://stackoverflow.com/questions/60174/how-can-i-prevent-sql步噴射功能於PHP)。 –

+0

@AlexHowansky還沒有;-)一旦它起火,是的。 –

回答

1

在您的兩個connect()insertdata()方法,你使用局部變量$mysqli,而不是實例變量 。您應該在實例方法中使用$this->mysqli而不是$mysqli。所以,你的connect()insertdata()方法將是這樣的:

function connect(){ 
    $hostname = "localhost"; 
    $username = "root"; 
    $password = ""; 
    $database = "demodatabase"; 
    $this->mysqli = new mysqli($hostname, $username, $password, $database); 
    /* check connection */ 
    if (mysqli_connect_errno()) { 
     printf("Connect failed: %s\n", mysqli_connect_error()); 
     exit(); 
    } 
    return true;    
} 

function insertdata($a, $b){ 
    $insert_row = $this->mysqli->query("INSERT INTO tb_user (id, user, password, status) VALUES('','".$a."', '".$b."', '')"); 
    if($insert_row){ 
     print 'saved'; 
    }else{ 
     die('Error : ('. $this->mysqli->errno .') '. $this->mysqli->error); 
    } 
} 

旁註:瞭解prepared statement因爲現在你的查詢是容易受到SQL注入攻擊。另見how you can prevent SQL injection in PHP

+0

非常感謝:)併爲建議。 – Krixnaas