简体   繁体   中英

PHP:Mysqli_real_escape_string

i'm having an issue with this piece of code and i cant see where the problem .

    <?php 
require_once("config.php");
class MySQLDatabase{
    private $connection;
    function _construct(){
        $this->open_connection();
    }
    public function open_connection(){
        $this->connection=mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
        if(!$this->connection){
            Die("Database Connection Problem : ".mysqli_connect_errno()." : ".mysqli_connect_error());
        }
        }

    public function close_connection(){
        if(isset($this->connection)){
            mysqli_close($this->connection);
            unset($this->connection);
        }
    }
    public function query($sql){
        $sql=mysql_prep($sql);
        $result=mysqli_query($this->connection,$sql);
        confirm_query($result,$sql);
        return $result;
    }
    public function mysqli_prep($string){
        global $connection;
        $safe_string=mysqli_real_escape_string($this->connection,$string);
        return $safe_string;
    }
    private function confirm_query($result,$sql){
        if(!$result){
            Die("Database query Problem : ".$sql);
        }
    }

}
$database=new MySQLDatabase();
$db=& $database;
 ?>

And i try to run the code bellow on Index.php

<?php
require_once("../includes/database.php");
echo "Is this working?";
echo $database->mysqli_prep("sss");
?>

But I receive this Error

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in \\includes\\database.php on line 29

The error is saying that the $this->connection you use in MySQLDatabase::mysqli_prep() is null . That's because it was never initialized.

Your class constructor needs to start with two underscores instead of one:

function __construct(){
    $this->open_connection();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM