2017-04-25 107 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