start PHP echo over every fourth mysql table row - php

I have a set of image url's in a database which I am echoing into an <img>tag to display on a website.
I am using bootstrap and have my basic model set up like this:
<div class="row-fluid gallery">
<div class="span3">
<img src="some fancy url here for the image">
</div>
</div>
Now if you have ever used bootstrap you know once that span3 reaches 12 (basically when 4 images are displayed in the row). You must start the above all over to keep the images all in line.
I have a PHP script below that echoes out the image source and the above layout. The problem is, I have more than 4 images to echo out. I removed credentials for security purposes.
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM gallery");
while($row = mysqli_fetch_array($result))
{
echo "<div class='row-fluid gallery'>";
echo "<div class='span3'>";
echo"<img src='". row['image_url']."'>";
echo "</div>";
echo "</div>";
}
mysqli_close($con);
My question is how do you do something like:
for every 4th image {
<div class="row-fluid gallery">
<div class="span3">
<img src="some fancy url here for the image">
</div>
</div>
}
Basically, I can say it in English and know what I need. But I can't say it in PHP and have it know what I need. Any help would be appreciated.

Create a counter variable outside the loop and check every fourth
$i = 1;
while($row = mysqli_fetch_array($result))
{
// do every time
if($i % 4 == 0)
{
// do only each 4th time
}
$i++;
}

$counter=0;
while($row = mysqli_fetch_array($result))
{
echo "<div class='row-fluid gallery'>";
echo "<div class='span3'>";
echo"<img src='". row['image_url']."'>";
echo "</div>";
echo "</div>";
$counter++;
if (!($counter%4))
// do your fancy staff, this is the forth image
}

Related

Adding HTML inside PHP problems

Currently when using the below code, I get website that looks like this:
Image here (Had to paint out some info due to GDPR)
This is the code used:
<div class="page group">
<div class="section">
<div class="col span_1_of_3">
<div id="outer_wrapper">
<div id="inner_wrapper">
<?php
$query = "SELECT * FROM sales WHERE ident ='".$currentName."' AND status ='Venter' ORDER BY STR_TO_DATE(date, '%d.%m.%Y') DESC";
if ($result = $mysqli->query($query)) {
$num_rows = 0;
while ($row = $result->fetch_assoc()) {
$num_rows++;
if ($num_rows > 0) {
echo '<div class="box">';
echo '<div class="Nwrapper">';
echo '<div id="NformContent">';
echo
"<tr><br>
<td><b>{$row['date']}</b></td><br>
<td> {$row['name']} </td> <b>/</b>
<td>{$row['gsm']} </td><br>
<td> {$row['email']} </td><br><br>
<td> <b>Info</b> <br> {$row['pp']} </td><br>
<td>Portering: {$row['transfer']}</td><br>
<td><a href='delete.php?id={$row['id']};' class='aRS'>Oppdater status</a><a onClick=\"javascript: return confirm('Ønsker du å angre salget?');\" href='delete.php?id={$row['id']};' class='aR'>Slett salg</a></td><br><br>
</tr>";
echo '</div>';
echo '</div>';
echo '</div>';
} else {
echo "No appointments";
break;
}
}
/*freeresultset*/
$result->free();
}
?>
</div> <!-- inner_wrapper -->
</div> <!-- outer_wrapper -->
</div> <!-- col span_1_of_3 -->
</div> <!-- section -->
</div> <!-- page group -->
<div class="lineWrapper"></div><br>
What I want to do is to hide the top horizontal boxes if the query return no value(0 number of rows(?) num_rows). I have tried doing it like this, and put my whole code inside the PHP query:
<?php
$query = "SELECT * FROM sales WHERE ident ='".$currentName."' AND status ='Venter' ORDER BY STR_TO_DATE(date, '%d.%m.%Y') DESC";
if ($result = $mysqli->query($query)) {
$num_rows = 0;
while ($row = $result->fetch_assoc()) {
$num_rows++;
if ($num_rows > 0) {
?>
<div class="page group">
<div class="section">
<div class="col span_1_of_3">
<div id="outer_wrapper">
<div id="inner_wrapper">
<?php
echo '<div class="box">';
echo '<div class="Nwrapper">';
echo '<div id="NformContent">';
echo
"<tr><br>
<td><b>{$row['date']}</b></td><br>
<td> {$row['name']} </td> <b>/</b>
<td>{$row['gsm']} </td><br>
<td> {$row['email']} </td><br><br>
<td> <b>Info</b> <br> {$row['pp']} </td><br>
<td>Portering: {$row['transfer']}</td><br>
<td><a href='delete.php?id={$row['id']};' class='aRS'>Oppdater status</a><a onClick=\"javascript: return confirm('Ønsker du å angre salget?');\" href='delete.php?id={$row['id']};' class='aR'>Slett salg</a></td><br><br>
</tr>";
echo '</div>';
echo '</div>';
echo '</div>';
?>
</div> <!-- inner_wrapper -->
</div> <!-- outer_wrapper -->
</div> <!-- col span_1_of_3 -->
</div> <!-- section -->
</div> <!-- page group -->
<div class="lineWrapper"></div><br>
<?php
} else {
break;
}
}
/*freeresultset*/
$result->free();
}
?>
When I save, it all looks good, the top boxes are all gone, but now if the number of rows is higher then 0, and there are some value to show, it looks like this(each displays in a vertical order):
Image here
Any suggestions on how I can get this to work like I want it to?
There is while loop. Inside loop you open table row put chunk as $num_rows and close row, than goes another chunk in it's own row.
While loop works as loop - chunk after chunk - end of loop;
I'm not sure - you want them all horizontally? In one row?
Actually, you don't need any table for this, this isn't tabular content, more appropriate would be section or div or something similar.
Whatever you pick, for now it would be a 'box';
this is how it should go:
open a box,
query, fetch - if is empty do nothing {}
if isn't empty - write down chunk after chunk,
close box;
With no chunks it will be empty box - you can hide it with .css (or not...)
Other solution is to assign all chunks to variable $x.= chunk
and then - if (x) is not empty - open a box - write it (x) down - close box;
If the output (x) is big, may cause problem.
Next one solution - workaround :
$box = '<div>'; // echoing $box will open a box
query, fetch, if empty do nothing;
if not empty output - echo $box write first chunk, unset $box - following chunks won't echoing $box,
after loop, if $num_rows > 0 close box (if 0 rows there is no open box)

this is my php code to view multiple images from database.but i can only see one image in front end.please help me

<?php
$servername = "*****";
$username = "****";
$password = "";
$dbname = "****";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$product_id = intval($_GET['product_id']);
// make sure its only an id (SQL Incjection problems)
$sql = "SELECT * FROM product_gallery WHERE pid=$product_id";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
while ($row = mysqli_fetch_array($result)) {
echo"<div class='tg-productbox'>";
echo" <div id='tg-thumblider' class='tg-thumblider tg-productgalleryslider owl-carousel'>";
echo" <figure class='item'><img src='$row[product_image]' alt='image description'></figure>";
echo" </div>";
echo" </div>";
echo" </div>";
};
} else {
echo "0 results";
}
$conn->close();
?>
This is my php code to view multiple images from database.but I can only see one image in front end.please help me..there is a main image and a slider to view to multiple images. It is similar to how we see product images in a shopping site
this is my php code to view multiple images from database.but i can only see one image in front end.please help me..there is a main image and a slider to view to multiple images.its is similar to how we see product images in a shopping site
There are some other mistakes like one extra closing div in loop and semicolon }; which not necessary.
Try something like below if you are getting multiple records it will definitely work.
while ($row = mysqli_fetch_array($result)) {
extract($row);
?>
<div class='tg-productbox'>
<div id='tg-thumblider' class='tg-thumblider tg-productgalleryslider owl-carousel'>
<figure class='item'>
<img src="<?php echo $product_image; ?>" alt="image description">
</figure>
</div>
</div>
<?php
}
Changes
Remove id='tg-thumblider' from echo "<div id='tg-thumblider' class='tg-thumblider. ID must need to be unique. According to the code provided, In while loop, every <div> will have same ID, which is wrong. So, either remove that ID or give some unique ID to each div.
Remove extra echo "</div>";
Remove ; from closing of while loop.
Code:
<?php
if ($result->num_rows > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<div class='tg-productbox'>";
echo "<div class='tg-thumblider tg-productgalleryslider owl-carousel'>";
echo "<figure class='item'><img src='".$row['product_image']."' alt='image description'></figure>";
echo "</div>";
echo "</div>";
}
}?>

PHP if statement inside for loop and append result in divs

Although I have resorted to stackoverflow for answers in the past many times but this is my first ever question on stackoverflow. I researched a lot about my issue and couldnt get answer to this specific issue. Hope posting actual question might help.
So here it is:
I have 2 divs in artwork.php
echo '<div id="on_going_art"></div>';
echo '<div id="completed_art"></div>';
My DB has 2 tables: artwork and user_hour_log
each user_id can have multiple art_id assigned to it and each art_id can have multiple user_hour_log entries.
Say $art[] is an array with multiple art_id in it and I am getting user_id from cookie:
for ($i=0; $i<count($art); $i++){
$query2= "SELECT *, SUM(total_time) AS total_time FROM user_hour_log WHERE user_id = '".$user_id."' && art_id = '".$art[$i]."'";
$result2 = mysqli_query($conn, $query2);
$row2 = $result2 -> fetch_assoc();
$hours_completed_artwork = $row2['total_time'];
$query3= "SELECT * FROM artwork WHERE winner_user_id = '".$user_id."' && art_id = '".$art[$i]."'";
$result3 = mysqli_query($conn, $query3);
$row3 = $result3 -> fetch_assoc();
$highest_bid_hours = $row3['highest_bid_hours'];
Here I am checking if $hours_completed_artwork is less than $highest_bid_hours, then append in #on_goin_art else append in #completed_art respectively:
if($hours_completed_artwork < $highest_bid_hours) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#on_going_art").append("
echo "<div class=\"row box1\">";
echo "<div class=\"col-xs-4 col-sm-4 col-md-4\">";
echo "<img class=\"img-responsive thumbnail\" src=\"http://i.imgur.com/jYea7Id.jpg?1\">";
echo "</div>";
echo "<div class=\"col-xs-8 col-sm-8 col-md-8\">";
echo "<h6 >"'.$row3['artwork_name'].'"<span id=\"percentage\">"'.number_format($hours_completed_artwork/ $highest_bid_hours *100,0).'"%</span> </h6>";
echo "</div>";
echo "</div>";
");
});
</script>';
} else if($hours_completed_artwork >= $highest_bid_hours) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#completed_art").append("
echo "<div class=\"row box1\"> \n";
echo "<div class=\"col-xs-4 col-sm-4 col-md-4\"> \n";
echo "<img class=\"img-responsive thumbnail\" src=\"http://i.imgur.com/jYea7Id.jpg?1\"> \n";
echo "</div> \n";
echo "<div class=\"col-xs-8 col-sm-8 col-md-8\"> \n";
echo "<h6 >'.$row3['artwork_name'].'<span id=\"percentage\">100% </span> </h6> \n";
echo "</div> \n";
echo "</div>";
");
});
</script>';
The problem is the append doesnt work, if I append just the strings eg: 'incomplete' and 'complete' it appends perfectly in right divs but it doesnt do it with my code.
I tried closing php tags right before including script tags that dint work either.
I have included Google CDN jquery links, tried changing position of script tags.
Sorry for such a long question. Hope it makes sense.
Here is a working snippet:
$row3['artwork_name'] = 'Some name';
$hours_completed_artwork = 40;
$highest_bid_hours = 50.00;
$percentage = $hours_completed_artwork < $highest_bid_hours ? number_format($hours_completed_artwork/ $highest_bid_hours *100,0) : 100;
$html = '<div class="row box1">\'+
\'<div class="col-xs-4 col-sm-4 col-md-4">\'+
\'<img class="img-responsive thumbnail" src="http://i.imgur.com/jYea7Id.jpg?1">\'+
\'</div>\'+
\'<div class="col-xs-8 col-sm-8 col-md-8">\'+
\'<h6 >'.$row3['artwork_name'].'<span id="percentage">'.$percentage.'%</span> </h6>\'+
\'</div>\'+
\'</div>';
$snippet = '<script type="text/javascript">
$(document).ready(function() {
$("#on_going_art").append(\''.$html.'\');
});
</script>';
echo '<div id="on_going_art"></div>';
echo $snippet;
I refactored the code to make it more maintainable. In javascript you cannot just throw html into an append function. New lines need to be concatenated using + and single or quotes. That is built in now. Also since only the percentage is either 100 or variable, i put that lot into one variable.
Your quotes are messed up.
And you have multiple echos inside the string, I guess you just copied the code and put it into the string.
It would be easier to build the html first, put it into a var, then use it:
if($hours_completed_artwork < $highest_bid_hours) {
$html = "<div class=\"row box1\">
<div class=\"col-xs-4 col-sm-4 col-md-4\">
<img class=\"img-responsive thumbnail\" src=\"http://i.imgur.com/jYea7Id.jpg?1\">
</div>
<div class=\"col-xs-8 col-sm-8 col-md-8\">
<h6 >".$row3['artwork_name']."<span id=\"percentage\">".number_format($hours_completed_artwork/ $highest_bid_hours *100,0)."%</span> </h6>
</div>
</div>";
echo "<script type=\"text/javascript\">
$(document).ready(function() {
$(\"#on_going_art\").append('".$html."');
});
</script>";
//....
Even better would be the use of HEREDOC or NEWDOC
Anyway the structure seems a little odd to me. Why don't you include the html via php in first place? Does it really have to be added later via javascript?

retrieve image from mysql database to array php

By compiling this, display three image get my database and show it, when i click each image popup window show last image of my database.I want to know how to display the particular image, when i click first image,then popup window show first image and description, as well as same way second and third image. check to array loop in this code...
enter code here
<?php
$sql=mysql_query("select * from product_reg")or die(mysql_error());
while($row=mysql_fetch_array($sql))
{
$productname=$row['productname'];
$productid=$row['productid'];
$description=$row['description'];
$image=$row['image'];
$firstN = array();
$i=0;
$firstN = '<img src="'.$row ['image'].'">';
echo ' <a href="#" class="big-link" data-reveal-id="myModal" name="image" style="float:left;margin:100px 0 100px 100px;"> ' ; echo $productname;echo $firstN[$i];
$r=$firstN[$i];
echo '</a>';
$i++;
}
?>
<div id="myModal" class="reveal-modal">
<form>
<table>
<tr><td><?php echo $r; ?></td>
<td><h1>Reveal Modal Goodness</h1>
<p>This is a default modal in all its glory, but any of the styles here can easily be changed in the CSS.</p></td>
<a class="close-reveal-modal">×</a>
</div>
</body>
</html>
I guess you have the images stored in the database like BLOB data. If so you need to create a handler to retrieve those images and render them as image/[mime]...
So in short.
In your code you need to create a new file iz get_image.php in it you need to make a request to the server and retrieve the image so you can send it to the client.
In your code you need to change the image path to the handler path with some query parameters.
$firstN = '<img src="get_image.php?imageid='.$row ['productid'].'">';
There are a lot information how to render the image to the client from the internet.
may be you have to declare your $firstN = array(); and then incrementor $i=0; out of while loop and put in array like this:
$firstN[$i] = '<img src="'.$row['image'].'">';
below is the full code:
<?php
$sql=mysql_query("select * from product_reg")or die(mysql_error());
$firstN = array();
$i=0;
while($row=mysql_fetch_array($sql))
{
$productname=$row['productname'];
$productid=$row['productid'];
$description=$row['description'];
$image=$row['image'];
$firstN[$i] = '<img src="'.$row['image'].'">';
echo '<a href="#" class="big-link" data-reveal-id="myModal" name="image" style="float:left;margin:100px 0 100px 100px;"> ';
echo $productname;
echo $firstN[$i];
$r=$firstN[$i];
echo '</a>';
$i++;
}
?>
Updates:
You have a space here:
$firstN[$i] = '<img src="'.$row['image'].'">';
//-----------------------------^----here at this code block;
To get the last image , you need to modify your query to have SORT BY productid DESC
To display the images
echo "<a href='xxx.php?imgid=$image'><img src='yourimagesfolderpath/$image.jpg'> </a>";
to navigate in the images , you have to use JQUERY

PHP MYSQL while loop with if statement echoing in wrong order

Ok, right now I trying to get a list to echo out from mysql using a while loop, but as you can see here http://institute4se.com/plan/ it's echoing in the wrong order. Why?
The reason for the if statements is to make the top and bottom pieces of the div echo only when the loop reaches the beginning of a new subsection.
If I remove the if statement the list echos out in order but then the beginning and end of the div echo every loop.
You can see my database aka $info here: http://i.stack.imgur.com/QMO2X.png http://i.stack.imgur.com/RsHdb.png
Any thoughts on how to fix it?
while($info = mysql_fetch_array( $data ))
{
if($info['subsection']=='0'){
echo "
<div class='menuSection'>
<div class='sectionHeader' id='header".$info['section']."'><img src='images/status_circ_empty.gif' alt='Section Empty' /><a href='index.php?s=".$info['section']."&ss=".$info['subsection']."'>".$titleArr[$info['section']]."</a><img src='images/arrow_".$currentArrow.".gif' alt='Arrow' class='arrow' /></div>
<ul class='sectionSubmenu' id='section".$info['section']."' style='display:".$currentSection."'>
";
}
else{
echo "<li><img src='images/status_circ_empty.gif' alt='Section Empty' /><a href='index.php?s=".$info['section']."&ss=".$info['subsection']."'>".$info['title']."</a></li>";
}
if($info['subsection']=='0'){
echo"
</ul>
</div>
";
}
}
You need to order records, add ORDER BY subsection ASC to the query.
Here is the fixed code for anyone who is interested:
while($info = mysql_fetch_array( $data ))
{
// if the current subsection is a new section
if($info['subsection']==0){
// if the current section is NOT the first section
if($info['section']!=0){
// end the section div
echo "
</ul>
</div>
";
}
// start the section div and add the section header
echo "
<div class='menuSection'>
<div class='sectionHeader' id='header".$info['section']."'><img src='images/status_circ_empty.gif' alt='Section Empty' /><a href='index.php?s=".$info['section']."&ss=".$info['subsection']."'>".$titleArr[$info['section']]."</a><img src='images/arrow_".$currentArrow.".gif' alt='Arrow' class='arrow' /></div>
<ul class='sectionSubmenu' id='section".$info['section']."' style='display:".$currentSection."'>
<li><img src='images/status_circ_empty.gif' alt='Section Empty' /><a href='index.php?s=".$info['section']."&ss=".$info['subsection']."'>".$info['title']."</a></li>
";
}
// if the current section is not a new section
else{
// add the next submenu item
echo "<li><img src='images/status_circ_empty.gif' alt='Section Empty' /><a href='index.php?s=".$info['section']."&ss=".$info['subsection']."'>".$info['title']."</a></li>";
}
}
echo"
</ul>
</div>
";

Categories