connection with database with OOP mysqli extending class

后端 未结 1 1271
你的背包
你的背包 2021-01-25 21:08

I know must coding part of mysql bt new at mysqli. I am not able to execute these insert query to the database. I have searched a lot but couldn\'t find simple suggestion, or ma

相关标签:
1条回答
  • 2021-01-25 21:18

    In both of your connect() and insertdata() methods, you're using local variable $mysqli, not the instance variable public $mysqli;. You should use $this->mysqli instead of $mysqli in your instance methods. So your connect() and insertdata() methods would be like this:

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

    and

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

    Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.

    0 讨论(0)
提交回复
热议问题