dozug64282 2016-02-16 17:44
浏览 39
已采纳

如何使用PHP回显基于MySQL数据库的动态html片段?

I'm trying to create an image gallery with a for loop iterated by a counter of database rows. To make it more clear: for each row in the table, get only the id(primary index) number and the image link from the server (not all the info in the row). With that information, echo an HTML image tag with the link inside the 'src=' and the id inside the 'alt='.

Two problems here:
1- the id number of the first row isn't zero.
2- I don't have a clue on how to get the total number of rows and to fetch only those two informations (id and img source).

That way, I could subtract the total number of rows minus the id number of the first row and using it to put an end on the loop.

So how to echo this dynamic html snippet based on my databse with PHP?

My code:

<?php

$link = mysqli_connect('localhost','user','pass','db');
$result = mysqli_query($link, "SELECT * FROM `table`");
$rows = mysqli_num_rows($result);

/* free result set */
mysqli_free_result($result);

$caption = mysqli_query($link, "SELECT ");

for($i=0; $i < $rows; $i++) {
    echo "<img src='$imageURL' alt='$idNumber'>";
}

?>
  • 写回答

3条回答 默认 最新

  • dongshen9058 2016-02-16 18:48
    关注

    This is a really easy task.

    First we fetch the data from the database using mysqli_query to do the query.

    Then we use mysqli_fetch_array to get an array so then we can loop through it and echo each item.

    After that, we mysqli_num_rows to get the total number of rows returned and increment it by 1 so it is not zero.

    NOTE: Since you are going to increment the id to avoid getting a '0', don't to forget to minus '1' if you intend to use that id for some server-side purpose.

    $result = mysqli_query($link, "SELECT * FROM `table`"); //query sql
    $result_array=mysqli_fetch_array($result, MYSQLI_ASSOC);//return array from the query
    $count = mysqli_num_rows($result);                      //get numbers of rows received 
    
    foreach($result as $row){ //do a foreach loop which is really simple
        echo "<img src='". $row['img_column_name_from_db'] . "'  alt='" .$row['id_column_name_from_db'] + 1 . "'>"; //echo data from the array, + 1 to "$row['id_column_name_from_db']" so that 'alt=' doesn't start from '0'.
        } 
    echo $count;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 硬盘识别不了,需要初始化,可我的数据怎么办
  • ¥15 lvm2被mask了,怎么unmask都没用(标签-ubuntu|关键词-apt)
  • ¥15 交叉注意力机制的残差问题
  • ¥15 微信小程序:渲染收货地址时页面不显示
  • ¥20 win7 64位DirectShow提示初始化失败如何解决?
  • ¥20 小规模孤立词识别系统设计
  • ¥15 关于Java对接海康威视车牌识别一体机SDK是否需要固定外网的IP?
  • ¥15 Linux扩容时,格式化卡住了:vgdispaly查看卷组信息,没有输出
  • ¥18 关于#ubuntu#的问题:使用背景-工作职责内有七八台ubuntu系统的电脑,平时需要互相调取资料,想实现把这几台电脑用交换机组成一个局域网,来实现指定文件夹的互相调取和写入
  • ¥20 求一个简易射频信号综测仪