user3325376
user3325376

Reputation: 198

receive returned value by class in oop

i have a class like this :

<?php
class connection {
    public $db;

    public function __construct() { 
    $this->db = new mysqli('localhost', 'root', '', '');

    if($this->db->connect_errno > 0){
        die('error ' . $this->db->connect_error);
    }
    $this->db->set_charset("utf8");
    }

}

class masssave extends connection {
    public $sql;
    public function insert_all {
    // do some works
            if ( $sql = $this->db->query("INSERT INTO $db_name ($str_db_value) values ($str_form_value_found) ")) {
            return true;    
            }
            else {
            return false;
            }
    }


}
?>

in masssave class i seted $sql as public , now i want to use this class in some pages , like register page

$save = new masssave;
if ( $save->sql = true ) {
    echo 'ok';
} 
else {
    echo 'failed';
}

but the upper code is not working , it always echo 'ok' even the query was failed ,

i also use if ( $save->sql == true ) but this code always echo 'failed'

i am newbie in oop , but i think my php classes are ok , i think i am doing wrong way for checking returned value

Upvotes: 0

Views: 56

Answers (3)

sectus
sectus

Reputation: 15464

  1. replace $sql = $this->db->query with $this->sql = $this->db->query -- $sql - local variable. $this->sql - object property
  2. call proper method after $save = new masssave; use $save->insert_all()
  3. use comparison (but not assigment) $save->sql = true - assigment, $save->sql == true - comparison. Assigment reutrns value of variable, so $save->sql = true is always true.

Upvotes: 3

Darren
Darren

Reputation: 13128

It will always echo ok because you're setting the $save->sql to true

if ( $save->sql = true ) {

The above is a big NO NO.

What you want is to compare it, so using == to compare the values

if ( $save->sql == true ) {

It would be simpler to just do:

if($save->sql) {
    echo 'ok;
} else {
    echo 'fail';
}

the above if check is basically saying IF(TRUE) { SAY OK} ELSE { SAY FAIL}

Upvotes: 0

Kylie
Kylie

Reputation: 11759

This line should be...

if ( $save->insert_all() == true )

Because....First off, you are just checking if $save->sql is set, which will always echo true in your case.

Also you weren't even checking you were actually setting (= vs ==)

$save = new masssave;
if ( $save->sql = true ) 

Should be...

$save = new masssave;
if ( $save->sql == true ) {

But that will always return true anyways, because its just checking if the variable exists, which it does. What you really want is what I posted at the top. Because query is actually inside the insert_all function, which is where you are returning true or false.

Upvotes: 0

Related Questions