【问题标题】:PHP - foreach loop in mysql rowPHP - mysql 行中的 foreach 循环
【发布时间】:2016-12-28 09:19:17
【问题描述】:

我正在尝试生成动态图像,我正在使用 jquery 从 mysql db 传递图像的id 以产生动态结果,但它似乎只打印一张图像并不起作用,我的代码是这里

 <?php

 include 'conn.php';

 if (mysqli_connect_errno()) {
 printf("Connect failed: %s\n", mysqli_connect_error());
 exit();
}

 $query = "SELECT id FROM homebg";
 $result = mysqli_query($conn, $query);
 if ($result->num_rows > 0) {

 while($row = $result->fetch_assoc()) {
 foreach ($row as $value) {
        echo " 
        <img class=\"responsive-img col l3\" id=\"img\">
        <script>  
$('#img').attr(\"src\",\"getImageadmin.php?id=\"+".$value.");
$('#img').show();
</script> ";
    }
  }
}
mysqli_close($conn);
?>  

这里我想在每次迭代中将图像的值(id)一个一个传递给使用的jquery,以便它可以一个一个地打印图像

【问题讨论】:

  • 你为什么不用&lt;img class=\"responsive-img col l3\" src=\"getImageadmin.php?id=\"+".$value.\"&gt;这个?
  • ID 应该是唯一的 - 在循环中创建具有相同 ID 的图像
  • 我理解循环中的图像,但您不应该需要循环中的脚本

标签: php mysql loops mysqli foreach


【解决方案1】:

您的 $row 是一个数组,其中包含在您的查询中选择的所有字段(这里只是 id)。 所以你需要这样做:

while($row = $result->fetch_assoc()) {
    echo "<img class=\"responsive-img col l3\" id=\"img\">
    <script>  
    $('#img').attr(\"src\",\"getImageadmin.php?id=\"+".$row['id'].");
    $('#img').show();
    </script> ";
}

【讨论】:

  • 它给出非法字符串偏移 'id'
  • 如果你试试呢?
【解决方案2】:
while($row = $result->fetch_assoc()) {
 foreach ($row as $value): ?> 
        <img class="responsive-img col l3" class="img" src = getImageadmin.php?id=<?php $value ?>>;
<?php endforeach; } ?>

您甚至不需要使用 javascript/jquery。这解决了目的。如果您仍然需要使用 jQuery,请使用 append() 不要创建 id,因为它们是独一无二的。

【讨论】:

    猜你喜欢
    • 2016-10-25
    • 2015-10-29
    • 1970-01-01
    • 2016-09-02
    • 2016-09-26
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    相关资源
    最近更新 更多