0

I have created a class named "Connection" for DB queries:

class Connection{
 public $mysqli;

 public function read($query){  
  $result= $this->mysqli->query($query);

  $num_result=$result->num_rows;

  if($num_result>0){
   while($rows=$result->fetch_assoc()){

    $this->data[]=$rows;
  }          
   return $this->data;
  }
 }
}

This is how I'm calling my class:

$obj=new Connection("localhost","root","","testpaginate");

$query="SELECT * FROM paginate";
$result=$obj->read($query);
mysqli_free_result($result);

$queries="SELECT * FROM paginate where id=1";
$results=$obj->read($queries);
print_r($results);
?>

When I execute

$query="SELECT * FROM paginate";
$result=$obj->read($query);

it shows the right answer.

When I again execute

$queries="SELECT * FROM paginate where id=1";
$results=$obj->read($queries);

it shows current result with previous result

Why so? Any help is much appreciated.

1
  • 3
    because you reuse $this->data[] and append your data there. just set $this->data = array(); before you fill it; Commented Mar 4, 2015 at 13:52

3 Answers 3

2

It's a good practice to declare variables correct in your classes.

You should do this every time you use them (if not used for other purposes):

class Foo {
    private $data;

    public function read()
    {
        $this->data = array();

        //do your stuff here, i.e. in your loop
        while(...)
           $this->data[] = $row;

        return $this->data;
    }
}

There could also be the possibility where you don't want to have a private variable associated:

class Foo {

    public function read()
    {
        $data = array();

        //do your stuff here, i.e. in your loop
        while(...)
           $data[] = $row;

        return $data;
    }
}

Now $data is just a local variable.

Sign up to request clarification or add additional context in comments.

Comments

2

The issue is that you're appending to $this->data every time you call read. You need to reinitialise the array $this->data in the method:

if($num_result>0){
    $this->data = array();
    while($rows=$result->fetch_assoc()){
        $this->data[]=$rows;
    }
}

Comments

-3

I think you should not use the [] after $this->data. It means it will add rows to the array.

1 Comment

Sorry, but that's wrong, now the property will contain only the last row of the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.