【问题标题】:connection with database with OOP mysqli extending class使用 OOP mysqli 扩展类与数据库连接
【发布时间】:2017-09-22 21:44:22
【问题描述】:

我知道必须在 mysqli 编写 mysql bt new 的一部分。我无法对数据库执行这些插入查询。我搜索了很多,但找不到简单的建议,或者可能是我不明白。

未定义变量:C:\wamp\www\New folder\php\msqliconnect.php 中的 mysqli 在第 32 行

致命错误:在 C:\wamp\www\New folder\php\msqliconnect.php 第 32 行的非对象上调用成员函数 mysqli_query()

感谢任何帮助。

<?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);
            }
        }
    }

?>

【问题讨论】:

  • 您的代码容易受到SQL injection attacks 的攻击。您应该使用mysqliPDO 带有绑定参数的预准备语句,如this post 中所述。
  • @AlexHowansky 还没有 ;-) 一旦它启动,是的。

标签: php database class mysqli connection


【解决方案1】:

在您的connect()insertdata() 方法中,您使用的是局部变量 $mysqli,而不是实例变量 public $mysqli;。您应该在实例方法中使用 $this-&gt;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

【讨论】:

    猜你喜欢
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多