Reputation:
I have some question about MySQL in PHP.
This is my config code:
<?php
class Core{
public $connect;
public function __construct(){
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'fix';
$this->connect = new mysqli($host,$user,$password,$database);
if(!$this->connect) echo mysql_error();
}
public function siteTitle(){
$title = "title";
$tagline = "tagline";
return $title. " - ".$tagline;
}
public function load($file,$data){
extract($data);
require "$file.php";
}
public function searchResult(){
$query = $this->connect->query("SELECT * FROM `location`");
if($query->num_rows > 0){
$columns = $query->fetch_assoc();
return $columns;
}
}
public function locationStatus($id){
$location = $this->searchResult();
$locationId = $location['id'];
if($locationId == 1){
echo "Available <i class='ui icon circle green'></i>";
}elseif($locationId == 2){
echo "Under Counstruction <i class='ui icon circle orange'></i>";
}else{
echo "Unavailable <i class='ui icon circle red'></i>";
}
}
}
?>
I will display a result from searchResult() function in searchResult.php file:
<div style='border:1px solid #ccc; padding:3px;'>
<img src="asset/images/<?php echo "$data[image].jpg"; ?>" class='ui image medium' style='padding-right:10px;float:left' />
<h2 style='font-family:nexa;color:rgb(36,162,217);line-height:0;'><?php echo $data['title']; ?></h2>
<h4><span style='color:orange;'>Location Address: </span><?php echo $data['subtitle']; ?></h4>
<p><?php echo $data['description']; ?></p>
<br />
<p>
<i class='ui icon marker big orange'></i>Checkin: <?php echo $data['checkin']; ?> <i class='ui icon clock big orange'></i>Published at: <?php echo $data['published']; ?> Status: <?php echo $this->locationStatus($data['id']); ?>
</p>
<a style='' href='location/<?php echo $data['slug']; ?>' class='ui button blue'>READ MORE</a>
</div>
And the searchResult.php, i call it in Index.php with code:
<?php echo $this->load('templates/searchResult', $this->searchResult()); ?>
My question is:
Why the result from my sql query is not a looping? Although, I was looping it with a while loop?
Thanks. Sorry if my language is bad.
Upvotes: 0
Views: 1341
Reputation: 1391
public function searchResult(){
$query = $this->connect->query("SELECT * FROM `location`");
if($query->num_rows > 0){
while ($columns = $query->fetch_assoc())
{
$data[] = $columns;
}
}
return $data;
}
You need the while loop in the searchResult function.
Upvotes: 0
Reputation: 94662
If you want to call your View like this
<?php
echo $this->load('templates/searchResult', $this->searchResult());
?>
You will have to put the loop in the searchResult()
method, so that this one call will return all the rows.
public function searchResult(){
$query = $this->connect->query("SELECT * FROM `location`");
$rows = array();
if($query->num_rows > 0){
while ( $row = $query->fetch_assoc() ) {
$rows[] = $row;
}
}
return $rows;
}
Then in your View, loop over $data
Upvotes: 1