Novry
Novry

Reputation: 23

MySQL Subquery cannot loop data

I've problem in my script, the script cannot loop the data, the Results only one image

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 |
------------------------------

My Query

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

FYI i was delete the LIMIT 1 but error mysql_query(): Unable to save result.

Thanks for responded

Upvotes: 1

Views: 33

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

1.mysql_* is deprecated and removed library now. Quickly move towards PHP7 along with mysqli_* Or PDO library

2.Change code like below

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

Note:- Query is wide open to SQL INJECTION so try to use prepared statements of mysqli_* or PDO library

Upvotes: 1

Related Questions