我在PHP中有一些关于MySQL的问题。
这是我的配置代码:
<?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>";
}
}
}
?>
我将在searchResult.php文件中显示searchResult()函数的结果:
<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>
searchResult.php,我在Index.php中用代码:
调用它<?php echo $this->load('templates/searchResult', $this->searchResult()); ?>
我的问题是:
为什么我的sql查询的结果不是循环?虽然,我用循环循环它?
感谢。对不起,如果我的语言不好。
答案 0 :(得分:1)
如果您想像这样调用您的视图
<?php
echo $this->load('templates/searchResult', $this->searchResult());
?>
您必须将循环放在searchResult()
方法中,以便这一次调用将返回所有行。
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;
}
然后在您的视图中,循环遍历$data
答案 1 :(得分:0)
public function searchResult(){
$query = $this->connect->query("SELECT * FROM `location`");
if($query->num_rows > 0){
while ($columns = $query->fetch_assoc())
{
$data[] = $columns;
}
}
return $data;
}
你需要在searchResult函数中使用while循环。