gpt4 book ai didi

php - 如何在函数中返回mysql_fetch_array

转载 作者:行者123 更新时间:2023-11-29 11:48:34 24 4
gpt4 key购买 nike

我有一些关于 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']; ?> &nbsp;&nbsp;&nbsp;<i class='ui icon clock big orange'></i>Published at: <?php echo $data['published']; ?>&nbsp;&nbsp;&nbsp; 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查询结果不是循环?虽然,我用 while 循环来循环它?

谢谢。抱歉,如果我的语言不好。

最佳答案

如果你想像这样调用你的 View

<?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;
}

然后在您的 View 中,循环 $data

关于php - 如何在函数中返回mysql_fetch_array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34534086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com