tags:

views:

54

answers:

3

The following code results to an error

Call to a member function real_escape_string() on a non-object

But if place the ($this->conn = new mysqli) inside the escapedString($string) method, it will run without error. What can be the reason of the error? Thank you.

private $onMagicQuote;
private $conn;

function __contruct(){
    $this->conn = new mysqli($this->host, $this->uname, $this->pass, $this->db)
              or die('Problem in connection');
    if(get_magic_quotes_gpc())
        $this->onMagicQuote = true;
    else
        $this->onMagicQuote = false;
}

function escapedString($string){
    if($this->onMagicQuote)
        return $string;
    else
        return $this->conn->real_escape_string($string);
}
+4  A: 

Your constructor has a typo and thus will be never called.

function __contruct(){

replace by

function __construct(){
Pekka
hah what I mistake that I didn't spot after looking at it for some time.
thephpdeveloper
lol, that its a downer allways happens to everyone
useless
i see i'm debugging this all the time the only problem is the missing 's' i didn't notice that thank you for your help
@crane01 You're welcome. You can accept the answer using the check mark sign to the left to close it.
Pekka
A: 

Crane, please note:

Note: OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error() function or the mysqli->connect_error property like in the examples above.

That means your "or die(..)" construct will never be executed. conn will always be an object but not a "connection object".

See http://de3.php.net/manual/en/mysqli.connect.php for example on how to check for connection errors.

Regards aefxx

aefxx
A: 

The problem is that the $this->conn object hasn't connected to the database.

See, in the constructor, the vars $this->host, $this->uname, $this->pass and $this->db are all null (since you haven't set them already, and they aren't static), therefore, no successful connection can be performed.

Mysqli's constructor doesn't fail (it returns an object), so the die is never executed, but when attempting to perform any action, it will fail since there is no valid connection opened.

The official way to check for connection errors is to use mysqli_connect_error() (notice that doing $this->conn->connection_error was broken in PHP 5.2.9-5.3.0).

You should both make sure the connection parameters are set properly before creating the mysqli object and check properly if the connection succeded.

Johnco