Add <br /> every 2 images from mysql in a variable - php

I'm trying to make this code insert a line break after 2 images when there are a total of 4 images. The Code listed below adds the line break after all images are displayed instead of after 2 images. Could someone please help me with this?
$images = "";
$i = 0;
while ($info = mysqli_fetch_array($imglist)) {
$style = $info['Style'];
$imgpath = $info['ImgPath'];
$standardimg = $info['StandardImg'];
$colorname = $info['ColorName'];
$smallimgwidth = $info['SmallImgWidth'];
$images = $images.
"<img src='$imgpath/$standardimg-Small.jpg'
alt = '$mill $style - $colorname'
title = '$mill $style - $colorname'
style = 'min-width:35px; max-width:$smallimgwidthpx;' / > ";
if (mysqli_num_rows($imglist) == 4) {
if ($i != 0 && $i % 2 == 1) {
echo '<br />';
}
}
$i++;
}

**Problem **
You are constructing the tags dynamically but in the process you are adding tags separately.
Solution
Add tag to your tags string being generated.
Code
$images = $images . '<br />';
In place of
echo '<br />';

Change
echo '<br />';
to
$images = $images . '<br />';
Just like that.
I little explanation: you're not 'grouping' br output with image output, since one goes into a variable (image) and the other is displayed immediately (br).

Related

Finding image src and adding prefix to image tag

I have a string that is for a blog, potentially it could have an unlimited number of images in this string, what I am trying to do is get all of the src="" and add a prefix to the url and use it as the hyperlink.
My string:
$test = 'Hello world
<img src="images/image1.jpg" />Line 2
<img src="images/image2.jpg" />Some text
<img src="images/image3.jpg" />';
I am able to prefix href. I am able to achieve this:
<img src="images/image1.jpg" />
<img src="images/image2.jpg" />
<img src="images/image3.jpg" />
This is my code so far:
$new = preg_replace('/(<img[^>]+src="([^\\"]+)"[^>]+\\/>)/','\\1',$test2);
echo $new;
I need to add foldername/as prefix in all the image src. What im trying to turn this into is the following:
<img src="foldername/images/image1.jpg" />
<img src="foldername/images/image2.jpg" />
<img src="foldername/images/image3.jpg" />
How can I do that?
To do this using DOMDocument rather than regex (a good reason is https://stackoverflow.com/a/1732454/1213708).
The code loads the HTML and then looks for all of the <img> tags. It first takes the value of src and adds the extra part to it. Then it creates a new <a> tag and also adds the (original) src value as the href attribute. It then replaces the <img> tag with the <a>, but adds the old value back into the <a>...
$dom = new DOMDocument();
$dom->loadHTML($test, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach ( $dom->getElementsByTagName("img") as $image ) {
$src = $image->getAttribute("src");
$image->setAttribute("src", "foldername/".$src);
$anchor = $dom->createElement("a");
$anchor->setAttribute("href", $src);
$image->parentNode->replaceChild($anchor, $image);
$anchor->appendChild($image);
}
echo $dom->saveHTML();
Not that it matters now, but here is a parsing solution without regex. I prefer #NigelRen solution actually now that its posted. However, here is a way to build a list of image urls without regex that could be used for solving your issue and provide further exploration. I haven't tested the code but i'm pretty fair on it working.
<?php
$html = 'some html here';
$sentinel = '<img src="';
$quoteSentinel = '"';
$done = false;
$offset = 0;
$imageURLS = array();
while (!$done) {
$nextImageTagPos = strpos($html, $sentinel, $offset);
if ($nextImageTagPos !== false) {
//*** Parsing
// Find first quote
$quoteBegins = false;
for ($i = $nextImageTagPos; $i < $nextImageTagPos + 100; $i++) {
if (substr($html, $i, 1) == $quoteSentinel) {
$quoteBegins = $i;
break;
}
}
// Find ending quote
$quoteEnds = false;
if ($quoteBegins !== false) {
for ($i = $quoteBegins + 1; $i < $quoteBegins + 1000; $i++) {
if (substr($html, $i, 1) == $quoteSentinel) {
$quoteEnds = $i;
break;
}
}
if ($quoteEnds !== false) {
// Hooray! now we are getting somewhere
$imgUrlLength = ($quoteEnds - $quoteBegins) - 1;
$imgUrl = substr($html, $quoteBegins + 1, $imgUrlLength);
// ***Requirements
/*
I have a string that is for a blog, potentially it could have an unlimited number of images in this string, what i am trying to do is get all of the src="" and add a prefix to the url and use it as the hyperlink.
*/
// But for brevity lets skip requirements and build an array of URLs.
$imageURLS[] = $imgUrl;
$offset = $quoteEnds + 1;
}
}
// Extract url
}
else {
$done = true;
}
}

Foreach loop for fotorama

im trying to use a foreach loop with the plugin fotorama.
What im trying to do is load one half sized image for the main gallery image. Which i have working in a foreach, but i want to use a full image for the data-full tag but i cant get it to work.
This is the working code.
<div class="fotorama"
data-allowfullscreen="native"
data-nav="thumbs"
data-fit="scaledown"
data-width="100%"
data-height="100%"
data-arrows="true"
data-click="true"
data-swipe="true">
<?php
$dirname = "admin/image-upload/uploads/";
$images = glob($dirname."*.*");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}
?>
</div>
this is what im trying to do.
<div class="fotorama"
data-allowfullscreen="native"
data-nav="thumbs"
data-fit="scaledown"
data-width="100%"
data-height="100%"
data-arrows="true"
data-click="true"
data-swipe="true">
<?php
$dirname = "admin/image-upload/uploads/";
$images = glob($dirname."*.*");
$dirname2 = "admin/image-upload/full/";
$images2 = glob($dirname2."*.*");
$fullImgs = "<img data-full=".$image2." src=".$image." /><br />";
foreach($fullImgs as $fullImg) {
echo $fullImg;
}
?>
</div>
thanks in advanced guys
Try this:
$dirname = "admin/image-upload/uploads/";
$images = glob($dirname."*.*");
$dirname2 = "admin/image-upload/full/";
$images2 = glob($dirname2."*.*");
$array = array_merge($images, $images2);
// Supossing both array have same length
$length = count($images);
for($i = 0; $j = $length; $i < $length; $i++, $j++) {
echo '<img data-full=".$images2[$j]." src=".$images[$i]." /><br />';
}
I think what you want is this:
<?php
$dirname = "admin/image-upload/uploads/";
$images = glob($dirname."*.*");
$dirname2 = "admin/image-upload/full/";
$images2 = glob($dirname2."*.*");
//assuming $images and $images2 are the same length...
foreach ($images as $k => $v) {
echo "<img data-full=".$images2[$k]." src=".$v." /><br />";
}
?>
Haven't tested, but should give the idea...
Your code won't work like this. If I understood you correctly you have the same image in big and small format in two different directories. To show them as pair you need to make a connection between those two files - because how should your script know which images belong together? You could use a database, but in your case I think it is easier to make a connection in the filename. For example, name the pictures in the directory for the small images
Image_7263.png
Image_0172.png
And so on. For the big images you simply append _BIG to the end of the name.
Then you use your foreach loop to loop through the directory for the small images. For each image in there, you append _BIG to the end of the filename and include it from the directory for the big ones.
$smallImages = glob ("/path/to/small/images/*.*");
foreach ($smallImages as $img)
{
$name = substr ($img, 0, strlen ($img)-4); //Remove the .png or .jpg
$bigImg = "/path/to/big/images/".name."_BIG.jpg"; // or whatever image type you are using
echo "<img data-full=\"".$bigImg."\" src=\"".$img."\" />
}

Showing a variable more than once depending on another variable (SQL)

I want to show a variable (which is an image) a certain amount of times depending on the number from a different column.
So I want to have $image shown $numberofratings times (which is up to 5). I'm pretty new to SQL, so I'm probably missing something quite basic, but thankyou to anyone who helps!
<?
$query = mysql_query("SELECT * FROM alex_demo23");
while ($row = mysql_fetch_array($query)){
$rating=$row['rating'];
$numberofratings=$row['numberofratings'];
$image = '<img src="images/star.png">';
echo ("addMarker(Rated: $rating $image from $numberofratings reviews');\n");
}
?>
Just use a for() or a str_repeat:
$image = '';
for($i=0; $i<$numberofratings; $i++){
$image .= '<img src="images/star.png">';
}
Or
$image = str_repeat('<img src="images/star.png">', $numberofratings);
This should do it:
$image = "";
for ($i = 0; $i < $row['numberofratings']; $i++) {
$image .= '<img src="images/star.png">';
}
There's no error checking to make sure that the data is valid, but it should be a start.

Splitting image result into Pages

I have this code that shows all the images inside 'images' directory but it is very annoying because all the images are showing on a single page :/
how could i split those images on multiple pages ?
here is the code
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<?php
$files = glob("images/*.*");
echo '<div id="design">';
for ($i=0; $i<count($files); $i++) {
$num = $files[$i];
if ($i%3==0){echo '<div class="Row">';}
echo '<img class="img" width="250px" height="250px" src="'.$num.'" alt="random image" />';
if ($i%3==0){echo '</div>';}
}
echo '</div>';
?>
Pagination! Here's a starting point:
// glob list of images
$files = glob('images/*');
// for consistency, you'll have to sort the resulting array...
natcasesort($files);
// get a page number from a query string e.g: ?page=1
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
// filter_input returns null if there is no page value in the qs,
// so let's check that and add a default value if we need to
$page = $page ?: 1;
// slice the array! get a subset of the files array based on
// an offset (page number) and length (results per page)
$resultsPerPage = 5;
$slice = array_slice($files, (($page - 1) * $resultsPerPage), $resultsPerPage);
You can now display your subset of results as normal. Of course you'll have to supply a series of links for each page... That's straightforward: get the length of your $files array, and use your $resultsPerPage value to figure out how many pages you need to display.
Hope this helps :)
First, try replacnig this line with something more rubust. This will return all files (image or anything else) unless you are sure that only image files are in the folder:
$files = glob("images/*.*");
The $files will result in an array with paths to the images, you can easily use this feature to display only the number of images you want in a page.
like this:
<?php
$imagesPerPage = 10;
if(!isset($_GET["start"]))
{
$start = 0;
}
else
{
$start = $_GET["start"];
}
$files = glob("images/*.*");
for($i = $start; $i < $start + $imagesPerPage; $i++)
{
if(isset($files[$i]))
{
echo "<img src=\"".$files[$i]."\" width=\"100\" height=\"100\" />\r\n";
}
}
$start = $start + $imagesPerPage;
echo "<br />\r\n";
echo "NEXT";
?>
You can follow the same rules and make a pervious link as well!
Please note, stopping (disabling) NEXT or Pervious links is up to yourself!

Random image picker PHP

$images = array();
$images[0][0] = "boxes/blue.jpg";
$images[0][1] = "blah.html";
$images[1][0] = "boxes/green.jpg";
$images[1][1] = "blah.html";
$images[2][0] = "boxes/orange.jpg";
$images[2][1] = "blah.html";
$images[3][0] = "boxes/pink.jpg";
$images[3][1] = "blah.html";
$images[4][0] = "boxes/purple.jpg";
$images[4][1] = "blah.html";
$images[5][0] = "boxes/red.jpg";
$images[5][1] = "blah.html";
$images[6][0] = "boxes/yellow.jpg";
$images[6][1] = "blah.html";
$i = 0;
*echo "<a href='" . $images[0][1] . "'><img src='" . $images[0][0] . "' /></a>";
$boxes = array();
while($i<5)
{
$rand = rand(0,(sizeof($images)-1));
//echo $rand;
$slice = array_splice($images, $rand);
$boxes[$i] = $slice;
$i++;
}*
I am trying to get a random image picker to choose from a list of images provided by the $images array. However, I am unable to fill the $boxes array with anything other than "Array". Can anyone tell me why? Any help is much appreciated
UPDATE
I am now using the code below and it breaks whenever it comes across an empty element. Unless i am very much mistaken, shouldn't splice patch up holes like that?
$rand = rand(0,(sizeof($images)));
array_splice($images, $rand);
$i = 0;
while($i<5)
{
echo "<a href='" . $images[$i][1] . "'><img src='" . $images[$i][0] . "' /></a>";
$i++;
}
This might be a nicer way of doing it:
foreach (array_rand($images, 5) as $key) {
$boxes[] = $images[$key];
}
Slightly off topic, but wouldn't it be easier in this case (picking 5 items from a list of 6) just to pick one element and discard it from the original array, and then use the original? This will also ensure you do not get duplicates in the resultant array.
I realise that you may have more than 6 items in the original, and may want less than 5 from it, but I'm talking specifically about the example posted.
array_splice() returns an array.
You can try something like this:
while($i<5)
{
$rand = rand(0,(sizeof($images)-1));
$boxes[$i] = $images[$rand];
$i++;
}

Categories