Home > other >  how can display img from DB
how can display img from DB

Time:12-28

I have more than one image saved in DB have same VID , I need help to display all images depending on column VID when VID == id ,this is my function it just display the first image.

    <body>

<?php
# database connection file
require_once('conect.php');
# fetching images
$sql1  = "SELECT * FROM villa where id=94; ";
$stmt = $pdo->prepare($sql1);
$stmt->execute();
$images = $stmt->fetchAll();
$num_of_row = $stmt->rowCount();
if ($stmt->rowCount() > 0) { ?>
    <div >
        <h4>All Images</h4>
        <?php foreach ($images as $image) {
            echo $num_of_row;
            for ( $i=0;$stmt->rowCount() >$i;$i  )
            {
                if ($image['id'] === $image['VID']){
                    echo $image['id'];
                    ?>
                    <img src="img/<?php echo ($image['imgV']);?>">
                <?php }
            }
        }?>
        
    </div>
<?php } ?>
</body>

CodePudding user response:

Maybe this:

 <img src="img  . '<?php echo ($image['imgV']);?>' . ">

But you should't use php code in your template. Php code base in. php files and templates in separate directory Learn more about mvc.. ) Sorry for my English))))

CodePudding user response:

Firstly, I added order by vid asc, id asc at the end of your SQL. It will help to sort the dataset at first.

Second, I using a variable $previousId to compare the current row and previous row's VID.

<body>
<?php
    # database connection file
    require_once('conect.php');
    # fetching images
    $sql1  = "SELECT * FROM villa where id=94 order by VID asc, id asc;";
    $stmt = $pdo->prepare($sql1);
    $stmt->execute();
    $images = $stmt->fetchAll();
    $num_of_row = $stmt->rowCount();
    if ($stmt->rowCount() > 0) {
        $previousId = null;
        ?>
            <div >
                <h4>All Images</h4>
                <?php
                    foreach ($images as $image) {
                        echo $num_of_row;
                        if($previousId != $image['VID']){
                            echo $image['id'];
                            $previousId = $image['VID'];
                        }
                        echo '<img src="img/' . $image['imgV'] . '">' . PHP_EOL;
                    }
                ?>
            </div>
        <?php
    }
?>
</body>
  • Related