Reputation: 2275
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.
Upvotes: 0
Views: 774
Reputation: 2200
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.
Upvotes: 2
Reputation: 74596
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;
}
}
Upvotes: 2
Reputation: 1754
I think you should not use the [] after $this->data. It means it will add rows to the array.
Upvotes: -3