PHP for loop not working - php

I have a for loop to go through an array I get from a web service that are paths to images, that I want to insert into and tags and print as much as there are in the array. The problem is the that for loop doesn't work as it is supposed to. It always prints out only one div with the correct image, and it is supposed to print out 4 of them. When I echo format 4 times by myself without using a loop, everything is fine.
Here is the code:
$format ='';
if(count($curl_odgovor_decoded) > 0)
{
$format ='';
for ($i=1; $i < count($curl_odgovor_decoded); $i++) {
if($curl_odgovor_decoded[0]['slika'.$i] != null)
{
$format.='<div class="col-sm-3 col-xs-6">
<a href="'.$curl_odgovor_decoded[0]['slika'.$i].'" title="slika'.$i.'" data-gallery="#blueimp-gallery">
<img class="img-responsive img-customer" src="">
</a></div>';
}
}
echo $format;
}
else
{
$format = ' <div class="col-sm-3 col-xs-6">
<p>Za ovaj oglas jos uvek nisu postavljene fotografije smestaja</p>
</div>';
echo $format;
}
If I do this it works fine(and I know that this is plain stupid, but I had to try it to test if something else was wrong and not the for loop):
echo '<div class="col-sm-3 col-xs-6">
<a href="'.$curl_odgovor_decoded[0]['slika1'].'" title="slika1" >
<img class="img-responsive img-customer" src="'.$curl_odgovor_decoded[0]['slika1'].'">
</a></div>';
echo '<div class="col-sm-3 col-xs-6">
<a href="'.$curl_odgovor_decoded[0]['slika2'].'" title="slika2" >
<img class="img-responsive img-customer" src="'.$curl_odgovor_decoded[0]['slika2'].'">
</a></div>';
echo '<div class="col-sm-3 col-xs-6">
<a href="'.$curl_odgovor_decoded[0]['slika3'].'" title="slika3" >
<img class="img-responsive img-customer" src="'.$curl_odgovor_decoded[0]['slika3'].'">
</a></div>';
echo '<div class="col-sm-3 col-xs-6">
<a href="'.$curl_odgovor_decoded[0]['slika4'].'" title="slika4" >
<img class="img-responsive img-customer" src="'.$curl_odgovor_decoded[0]['slika4'].'">
</a></div>';
I cannot find the problem with the for loop, why would it print out just one div with the image?

Since apparently everything is in $curl_odgovor_decoded[0], count($curl_odgovor_decoded) returns exactly 1, therefore it only loops once. It seems more sensible to use a foreach loop here:
foreach ($curl_odgovor_decoded[0] as $key => $slika) {
'... <a href="' . $slika . '" title="' . $key . '" ...';
}

Related

How can i store images in an array and with a for loop print them? PHP

I try to print images with a for loop but the images dont load.
<?php
$imagenes = array('1.png', '2.jpg', '3.png', '4.jpg','IMG_0105.JPG');
?>
<div class="container">
<div class="row">
<div class="col-md">
<?php
for ($i=0; $i < 4; $i++) {
echo '<img src = \"$imagenes[$i]\" width = \'100px\' height = \'100px\';>';
}
?>
</div>
</div>
</div>
The images are in the same folder as the .php file
Edit: Added additional solutions based on answer from #nik
This will never work because variables are not evaluated inside of single quoted strings.
Make sure that your use a string inside double quotes. Or use string concatenation to build the HTML tag. Also, you image tag has a semicolon inside of it that might break the tag.
So you can do this ...
echo "<img src=\"{$imagenes[$i]}\" width=\"100px\" height=\"100px\">";
or
echo "<img src=\"" . $imagenes[$i] . "\" width=\"100px\" height=\"100px\">";
or
<img src="<?= $imagenes[$i]; ?>" width="100px" height="100px">
or
<img src="<?php echo $imagenes[$i]; ?>" width="100px" height="100px">
Use foreach for this. And for concatinate string with var - use . (dot)
<?php
foreach ($imagenes as $image) {
echo '<img src = "'.$image.'" width = "100px" height = "100px">';
}
?>
This would make it simplier:
<div class="container">
<div class="row">
<div class="col-md">
<?php foreach ($imagenes as $url) { ?>
<img src="<?php echo $url ?>" width="100px" height="100px">
<?php } ?>
</div>
</div>
</div>
I think its the way you're escaping the characters, you can just use concatenation on $images:
<div class="container">
<div class="row">
<div class="col-md">
<?php
for ($i=0; $i < 4; $i++) {
echo '<img src = '.$imagenes[$i].' width="100px" height ="100px";>';
}
?>
</div>
</div>
</div>

PHP import images from directory into 2 column HTML row

I have found some PHP that I am trying to adapt onto my page but can not seem to get it to work. Here is the code:
<?php
$pagetitle = "Test Gallery";
$dirname = "img/folder_1/";
$images = glob($dirname."*.jpg");
?>
<?php $i=0; foreach($images as $image): ?>
<?php if($i%2 === 0) echo '<div class="row">' ?>
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
<?php if($i%2 === 0) echo '</div>' ?>
<?php $i++; endforeach ?>
I am trying to get the images to be pulled from a directory and each image is wrapped in a .col-sm-6 div then each 2 are wrapped in a .row div, then if there is an odd number of the files the last one would just be one .col-sm-6 div on its own. Below is the structure that I am trying to achieve:
<div class="row">
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
</div>
The IMAGE_NAME I would add something to pull through the imported filename so it can be displayed on the page and the IMAGE_SOURCE would be the images URL so for now please ignore those bits of text as I don't think it will affect this?
I am new to PHP and just can't seem to find why nothing is showing on the page unless this code is not suited to my needs?
P.s. if any of my syntax's are incorrect I apologies in advance.
$images will be filled by your golb
So basically you just edit the line
<?php if($i%2 === 0) echo '</div>' ?>
To
<?php if($i%2 === 1) echo '</div>' ?>
Here a more readable example:
<?php
$images = [
'https://via.placeholder.com/10x50','https://via.placeholder.com/20x50','https://via.placeholder.com/30x50','https://via.placeholder.com/40x50',
'https://via.placeholder.com/50x50','https://via.placeholder.com/60x50','https://via.placeholder.com/70x50',
];
?>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"/>
<?php
$cols = 2; // dividable by 12 please
for( $i = 0; $i < count($images) && $image = $images[$i]; $i++) {
if( $i%$cols == 0 ) { echo '<div class="row">'; }
echo '<div class="col-sm-' . 12/$cols . '">';
echo '<img class="lazy store-img" src="' . $image . '" alt="" title="">';
echo '<h3>IMAGE_NAME</h3>';
echo '<button href="#" class="btn btn-primary">Purchase Image</button>';
echo '</div>';
if( $i%$cols == $cols-1 ) { echo '</div>'; } /* here comes the magic :) */
}
if( count( $images )%$cols > 0 ) {
echo '</div>';
}
?>

Div tag around php code

I'm trying to configure my database data that is being pulled with php to look like my homepage.
I can't figure out what I need to do.
This is for a project for school, and I have very limited knowledge on php.
Here is my php script.
<?php
include('mysql_connect.php');
$dbh = con();
foreach($dbh->query("SELECT * FROM `Product` WHERE `ProductType` = 'memory' ",PDO::FETCH_ASSOC) as $row){
$Pname = $row['ProductName'];
$description = $row['description'];
$price = $row['ProductPrice'];
$ID = $row['ProductID'];
echo <div class="row">;
echo <div class="col-sm-4 col-lg-4 col-md-4">;
echo <div class="thumbnail">;
<img src="/var/www/html/Pictures/gigb75m_home.jpg" alt="">
echo "<div class="caption">";
echo "<h4 class="pull-right">$price</h4>";
echo "<h4>$Pname</h4>";
echo "<p>$description</p>";
echo "<p>$ID</p>";
}
?>
</div>
</div>
</div>
Here is my index that has my desired results.
<div class="row">
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<img src="/var/www/html/Pictures/gigb75m_home.jpg" alt="">
<div class="caption">
<h4 class="pull-right">$74.99</h4>
<h4>GIGABYTE GA-B75M
</h4>
<p>Micro ATX, LGA 1155, Intel B75 Express Chipset, 2200MHz DDR3 (O.C.), SATA III (6Gb/s), 7.1-CH Audio, Gigabit LAN, USB 3.0 - GA-B75M-D3H</p>
</div>
</div>
</div>
Picture of homepage: http://imgur.com/g72Wrxk
Any help/guidance is greatly appreciated, this is driving me crazy.
Use '.' for string concatinations.
For example:
echo '<h4 class="pull-right">' . $price . '</h4>';
You have to use single quote to echo content in your PHP script like this for instead :
echo '<div class="row">';
The single quotes are used to explain that it's a string to show. You have to do the same for your other echo part.
Or you can escape the HTML part from the PHP and replace by vars inside it like this :
<?php
include('mysql_connect.php');
$dbh = con();
echo '<div class="row">';
foreach($dbh->query("SELECT * FROM `Product` WHERE `ProductType` = 'memory' ",PDO::FETCH_ASSOC) as $row){
$Pname = $row['ProductName'];
$description = $row['description'];
$price = $row['ProductPrice'];
$ID = $row['ProductID'];
?>
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<img src="/var/www/html/Pictures/gigb75m_home.jpg" alt="">
<div class="caption">
<h4 class="pull-right"><?php echo $price; ?></h4>
<h4><?php echo $Pname; ?></h4>
<p>$description</p>
<p>$ID</p>
</div>
</div>
</div>
<?php
}
?>
</div>
Also you have to be careful about the row system of bootstrap to echo col-md-4 inside a row, you can add 3 items like this per row. So you have to close and reopen a row each time you fetch 3 elements to get a correct HTML structure.
You didn't supplied any information about your database, yet the first problem that's visible is your echo's
To output HTML through PHP you have to output pure strings.
An example for that would be ""
In PHP when you want to connect different kinds of inputs like variables and "" or '' etc you connect them with a dot.
For example:
$string = ' hello3';
echo "Hello 1 ".' hello2 '.$string;
The outcome will be:
Hello 1 hello2 hello3
I hope you got it the hang of it.

Best practice when echo repeated code

I have a question that bothers me for a long time. Lets say i have a code with several nested div's and span's. All these compose a square with an image inside.
echo '<div> <div> <div> <div> <span> <img src='.$image.'> </span></div></div></div>';
Only that this code has about 15 rows.
From what i know when echo-ing the results from db in that form i put in the loop the whole html code. It looks clumsy this way.
It is there a better practice ?
foreach ($query->result() as $row)
{
$row->address_link=strtolower($row->network);
echo '<li class="col-md-3 isotope-item '.$row->network.'">';
echo '<div class="portfolio-item img-thumbnail">';
echo '<table border="0"><tr>';
echo '<a href="order/'.$row->address_link.'/'.$row->value.'" class="thumb-info">';
echo '<img alt="" class="img-responsive" src="img/'.$row->address_link.'.png">';
echo '<span class="thumb-info-title">';
echo '<span class="thumb-info-inner">'.$row->value.' Euro</span>';
echo '</span>';
echo '<span class="thumb-info-action">';
echo '<span title="Universal" href="order/'.$row->address_link.'/'.$row->value.'" class="thumb-info-action-icon"><i class="icon icon-link"></i></span>';
echo '</span>';
echo '</a>';
echo '</div>';
echo '</tr><tr>';
echo '<span class="thumb-info-type">'.$row->value*$row->rate.' Eur</span>';
echo '</tr></table>';
echo '</li>';
}
If you are new to php you can define a function for this:
function wrapImage($src){
return '<div> <div> <div> <div> <span> <img src='.$src.'> </span></div></div></div>';
}
And just use echo wrapImage($src) where you need it with different params.
EDIT: consider following way of presenting the data:
<?php
$query = 'select * from Unicorns';
foreach ($query->result() as $row){
$row->address_link=strtolower($row->network);
?>
<!-- html -->
<li class="col-md-3 isotope-item <?php echo $row->network; ?>">
<div class="portfolio-item img-thumbnail">
<table border="0"><tr>
<a href="order/<?php echo $row->address_link.'/'.$row->value; ?>" class="thumb-info">
<img alt="" class="img-responsive" src="img/'.$row->address_link.'.png">
<span class="thumb-info-title">
<span class="thumb-info-inner"><?php echo $row->value; ?> Euro</span>
</span>
<span class="thumb-info-action">
<span title="Universal" href="order/<?php echo $row->address_link.'/'.$row->value ?>" class="thumb-info-action-icon"><i class="icon icon-link"></i></span>
</span>
</a>
</div>
</tr><tr>
<span class="thumb-info-type"><?php echo ($row->value*$row->rate); ?> Eur</span>
</tr></table>
</li>
<!-- /html -->
<?php } ?>
It is called spaghetti code .. and it is NOT the best practice but is better then your example in case the HTML is more then the PHP data.
first of all, dont use echo in loops (optimalization), store your output in variable and print it only once.
Repeated code can be stored inside function
function square($image){
return '<div> <div> <div> <div> <span> <img src='.$image.'> </span></div></div></div>';
}
$output = '';
while ($loop){
$output .= square($image);
}
echo $output

foreach first element add a class

image folder has 3 files
<img src='images/AAA_1.jpg'>
<img src='images/AAA_2.jpg'>
<img src='images/AAA_3.jpg'>
<img src='images/BBB_1.jpg'>
<img src='images/BBB_2.jpg'>
<img src='images/BBB_3.jpg'>
<img src='images/CCC_3.jpg'>
PHP is
foreach ($carousel as $image) {
if(strpos($image, 'AAA_') === 0){
echo "<div class='box'><img src='images/carousel/$image'/></div>";
}
}
so the output is
<div class='box'>
<img src='images/AAA_1.jpg'>
</div>
<div class='box'>
<img src='images/AAA_2.jpg'>
</div>
<div class='box'>
<img src='images/AAA_3.jpg'>
</div>
How can I add a first class on the fist box, looks like
<div class='box first'>
<img src='images/AAA_1.jpg'>
</div>
<div class='box'>
<img src='images/AAA_2.jpg'>
</div>
<div class='box'>
<img src='images/AAA_3.jpg'>
</div>
Use the key:
foreach ($carousel as $key=>$image) {
$first = $key == 0 ? ' first' : '';
if(strpos($image,'AAA_') === 0){
echo <<<EOD
<div class='box{$first}'>
<img src='images/carousel/{$image}.jpg'>
</div>
EOD;
}
}
Note: I used a heredoc statement for the echo as I prefer to echo multiple tags of HTML over multiple lines.
Simple: Use a flag.
$firstEchoed = FALSE;
foreach ($carousel as $image) {
if(strpos($image,'AAA_') === 0){
echo "<div class='box";
if ( ! $firstEchoed)
echo " first";
echo "'><img src='images/carousel/$image'/></div>";
$firstEchoed = TRUE;
}
}
You can use a boolean flag, or add count param to foreach:
foreach ($carousel as $i => $image)

Categories