问题
For some reasons mysql returns only last inserted element in table,could anyone give a tip what's wrong with my code? i'm just practicing php and trying to figure out best ways to make functions easily reusable(just practicing oop i mean). i know this is a bad way but it's only for practice purposes.
<!DOCTYPE html>
<html>
<head>
<title>Test Title</title>
</head>
<body>
<?php
class Database{
public $db;
public function __construct($host,$username,$password,$dbname){
$this->db=new MySQLi($host,$username,$password,$dbname);
}
public function getData(){
$query="SELECT * FROM artisan";
$result=$this->db->query($query);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
echo "ID: ".$row["id"]. "-Username: ".$row["username"]. ", "."Email: ".$row["email"]."<br>";
}
}else{
echo "No results found!";
}
}
public function getContent(){
$query="SELECT * FROM content";
$result=$this->db->query($query);
$values=array();
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$values=array(
"title"=>$row['title'],
"body"=>$row['body']
);
}
}
return $values;
}
}
$database=new Database('localhost','root','','test');
$database->getData();
$values=$database->getContent();
?>
<style type="text/css">
.container{
text-align:center;
}
</style>
<div class="container">
<?php
for($i=0;$i<count($values);$i++){
echo $values["title"]."<br>";
echo $values["body"]."<br>";
}
?>
</div>
</body>
</html>
回答1:
You should add each row to $values instead of replacing it each time.
Where you have:
$values=array(
"title"=>$row['title'],
"body"=>$row['body']
);
Change it to:
$values[] = array(
"title"=>$row['title'],
"body"=>$row['body']
);
And then where you have the display:
for($i=0;$i<count($values);$i++){
echo $values["title"]."<br>";
echo $values["body"]."<br>";
}
Change to:
foreach($values as $value){
echo $value["title"]."<br>";
echo $value["body"]."<br>";
}
Or using a FOR:
for($i=0;$i<count($values);$i++){
echo $values[$i]["title"]."<br>";
echo $values[$i]["body"]."<br>";
}
回答2:
you are reassigning $values to the last array you created each time, instead you should be adding the array you created to $values. use $values[] like below:
public function getContent(){
$query="SELECT * FROM content";
$result=$this->db->query($query);
$values=array();
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$values[]=array(
"title"=>$row['title'],
"body"=>$row['body']
);
}
}
来源:https://stackoverflow.com/questions/47702654/fetch-assoc-returns-last-inserted-elements