php - MySQL 子查询无法循环数据

标签 php mysql subquery

我的脚本有问题,脚本无法循环数据,结果只有一张图片

t_award

-------------------
| id | id_product |
-------------------
| 1  | 1          |
| 2  | 2          |
-------------------

t_image

------------------------------
| id | id_product | image    |
------------------------------
| 1  | 1          | img1.jpg |
| 2  | 1          | img2.jpg |
| 3  | 2          | pic1.jpg |
| 4  | 2          | pic2.jpg |
------------------------------

我的查询

<?php
        require ("koneksi.php");
        $perintah="SELECT *, 
                (SELECT image FROM `t_image` as tbl_t_image WHERE tbl_t_image .id_product = t_award.id_product LIMIT 1) as image_name
                FROM t_award
                where id='".$_GET['id']."'";

        $hasil=mysql_query($perintah);
        while ($data=mysql_fetch_array($hasil)) {
        echo'


        <div class="content-img oversize">
            <img src="ipf-panel/img/images_cont_part/'.$data['image_name'].'" alt="">
        </div>
        ';
        }
        ?>

仅供引用,我删除了 LIMIT 1 但错误 mysql_query():无法保存结果。

感谢回复

最佳答案

1. mysql_*现在已弃用并删除库。快速走向PHP7连同 mysqli_*或者 PDO图书馆

2.修改如下代码

<?php
    if(!empty($_GET['id'])){
        $id = $_GET['id'];
        require ("koneksi.php");
        $perintah="SELECT t_image.image FROM `t_award` LEFT JOIN `t_image` ON t_image.id_product = t_award.id_product WHERE id=$id";
        $hasil=mysql_query($perintah);
        while ($data=mysql_fetch_assoc($hasil)) {
            echo'<div class="content-img oversize"><img src="ipf-panel/img/images_cont_part/'.$data['image'].'" alt=""></div>';
        }
    }
?>

注意:- 查询对 SQL INJECTION 开放所以尝试使用 prepared statementsmysqli_*PDO图书馆

关于php - MySQL 子查询无法循环数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52419974/

相关文章:

php - php 中子类构造函数如何与父类构造函数交互?

php - 将图像存储在文件夹 laravel 中

php - 将 wordpress powered 站点中的所有标题转换为 "Capitalized"大小写

php - mysql 连接三个表并分组

php - 如何让 MySQL 对最新创建的行进行排序

MySQL:外键始终为0

php - Windows MYSQL 上的 XAMPP 将启动然后突然停止但 APACHE 工作正常

postgresql - Postgres 在 case 语句中引用子查询

sql-server - 是否可以在 SQL Server 2008 中使用存储过程作为子查询?

php - MySQL Sum(Total) 和 Sum(User) with ROLLUP