【问题标题】:How to display multiple fetched data?如何显示多个获取的数据?
【发布时间】:2016-09-24 14:18:40
【问题描述】:

我正在使用以下内容从数据库中获取最新文章:

//Latest Article
$title_query1 = "SELECT title FROM articles ORDER BY id DESC LIMIT 1";
$description_query1 = "SELECT description FROM articles ORDER BY id DESC LIMIT 1";
$content_query1 = "SELECT content FROM articles ORDER BY id DESC LIMIT 1";
$image_query1 = "SELECT image FROM articles ORDER BY id DESC LIMIT 1";

$title_result1 = mysqli_query($con, $title_query1) or die(mysqli_error($con));
$description_result1 = mysqli_query($con, $description_query1) or die(mysqli_error($con));
$content_result1 = mysqli_query($con, $content_query1) or die(mysqli_error($con));
$image_result1 = mysqli_query($con, $image_query1) or die(mysqli_error($con));

//Second Latest Article
$title_query2 = "SELECT title FROM articles ORDER BY id DESC LIMIT 2,1";
$description_query2 = "SELECT description FROM articles ORDER BY id DESC LIMIT 2,1";
$content_query2 = "SELECT content FROM articles ORDER BY id DESC LIMIT 2,1";
$image_query2 = "SELECT image FROM articles ORDER BY id DESC LIMIT 2,1";

$title_result2 = mysqli_query($con, $title_query2) or die(mysqli_error($con));
$description_result2 = mysqli_query($con, $description_query2) or die(mysqli_error($con));
$content_result2 = mysqli_query($con, $content_query2) or die(mysqli_error($con));
$image_result2 = mysqli_query($con, $image_query2) or die(mysqli_error($con));

但是,我不确定我该如何做这样的事情:

 <h1>Here is the first article: <?php $title_result1 ?><h1>
 <h2>Here is the first article description: <?php $description_result1 ?>

 <h1>Here is the second article: <?php $title_result2 ?><h1>
 <h2>Here is the second article description: <?php $description_result2 ?>

还有,这个方法不好吗?如果我要对 100 多篇文章执行此操作,会导致网页加载缓慢吗?

谢谢

【问题讨论】:

  • 从阅读表 JOIN 开始。编辑:是的,这将比使用单个查询获取所有数据并循环它们要慢
  • 这会非常缓慢地加载网页。相反,您应该执行SELECT title, description,content, image FROM articles ORDER BY id DESC LIMIT 100 之类的操作,然后使用循环遍历响应。

标签: php html sql mysqli


【解决方案1】:

您不需要对每一列进行一次查询。您可以通过 select * 获取一行的所有列。此外,如前所述,您可以获取任意多的行,然后循环遍历它们。

我更喜欢while 方法。示例,显示最近 100 篇文章

// fetch latest 100
 $sql = "SELECT * FROM articles ORDER BY id DESC LIMIT 100";

if ($result = mysqli_query($con, $sql)){
// got results, convert result object to array called $row

while ($row = mysqli_fetch_array($result)) {

// echo out $row array elements with 
//the column names from the database as array index

echo  '<h2>'. $row['title'] .'</h2>';  // example wrap results with HTML
echo '<b>' .$row['description'] .'</b>'; 
echo $row['content']; 
echo <img src="'.  $row['image'] .'" title="'.$row['description'].'">'; 
echo '<br>'; //so next result is on new line

}   // end of while loop

} else {    
//no result,  error 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-20
    • 2022-11-22
    • 2021-09-02
    • 1970-01-01
    • 2019-03-30
    • 2016-01-13
    • 1970-01-01
    • 2023-01-22
    相关资源
    最近更新 更多