Hi guys and thank you for your time. My question is regarding.
I am trying to loop over images in my folder along with a post in the database with the end result looking like this:
Post 1 Image 1
Post 2 Image 2
Post 3 Image 3
At the moment i get this result:
Post 1 Image 1
Post 1 Image 2
Post 1 Image 1
Post 2 Image 1
Post 2 Image 2
Post 2 Image 3
I do not want this result.
Below is my code:
$post_info = get_posts();
foreach ($post_info as $info){
$photos = glob('design/img/*');
foreach($photos as $photo) {
echo " <a href='feed.php?pid=".$info['post_id']." ' >
<div style='background:#FFF5C3'> <br> <h2> ".$info['person_mentioned']." </h2>
<h3 style='color: black'> ".$info['body']." </h3> </div> </a>";
echo " <img src='{$photo}' width='285px' height='200px' style='border: 5px solid black'>";
}
}
Thanks for your time.
Try this out (minus potential language specifics since I didn't actually run to check this code).. It's basically a regular for loop instead of a foreach.
$post_info = get_posts();
$photos = glob('design/img/*');
if (count($post_info) === count($photos)) { // According to your requirement, the counts would be the same
$count = count($post_info);
for ($i = 0; $i < $count; $i++) {
$info = $post_info[$i];
$photo = $photos[$i];
echo " <a href='feed.php?pid=".$info['post_id']." ' > <div style='background:#FFF5C3'> <br> <h2> ".$info['person_mentioned']." </h2>
<h3 style='color: black'> ".$info['body']." </h3> </div> </a>";
echo " <img src='{$photo}' width='285px' height='200px' style='border: 5px solid black'>";
}
}
Hope that helps :)
Getting image details from get_posts() and removing inner foreach loop may fix your problem.
Note: replace $info['something_like_post_image'] with your image field.
$post_info = get_posts();
foreach ($post_info as $info) {
//$photos = glob('design/img/*');
//foreach ($photos as $photo) {
echo " <a href='feed.php?pid=" . $info['post_id'] . " ' >
<div style='background:#FFF5C3'> <br> <h2> " . $info['person_mentioned'] . " </h2>
<h3 style='color: black'> " . $info['body'] . " </h3> </div> </a>";
echo " <img src='" . $info['something_like_post_image'] . "' width='285px' height='200px' style='border: 5px solid black'>";
//}
}
UPDATE
/*
* If your images have any naming convention like
* imageFileName = "image_{POST_ID}.jpg"
* then you can use below code (NO DATABASE ENTRY REQUIRED)
* (ie, For post #1 image file would be "image_1.jpg";
* and for post #2 image file would be "image_2.jpg")
*/
$post_info = get_posts();
foreach ($post_info as $info) {
//filename = image_1.jpg or image_2.jpg or...
$photoFileName = 'design/img/' . 'image_' . $info['post_id'] . '.jpg';
if (file_exists($photoFileName)) {
echo " <a href='feed.php?pid=" . $info['post_id'] . " ' >
<div style='background:#FFF5C3'> <br> <h2> " . $info['person_mentioned'] . " </h2>
<h3 style='color: black'> " . $info['body'] . " </h3> </div> </a>";
echo " <img src='" . $photoFileName . "' width='285px' height='200px' style='border: 5px solid black'>";
}
}
NOTE: You should have to keep a relation with each post against your unique image; otherwise you will not be able to get that unique image with your post, while listing.
Checkout below options to handle this situation.
You can keep image name in database (for each post, you can get your image name directly from database)
Use a naming convention for your images (for post #1 use unique image name (say image_1, for post #2 image_2 etc)
UPDATE - 2
If you are looking for a cycle-through images (without any condition), use below code
/*
* If you are looking for a solution that cycles each images
* along with each post, try this one
*/
$post_info = get_posts();
$photos = glob('design/img/*');
$numPhotos = count($photos) + 1;
//assuming your post# starts with 1
$imageId = 1;
foreach ($post_info as $info) {
//cycling
if ($imageId % $numPhotos === 0) {
$imageId = 1;
}
$photoFileName = 'design/img/' . 'image_' . $imageId++ . '.jpg';
//no need of this checking, since you are cycling
//if (!file_exists($photoFileName)) {
// $photoFileName = 'path/to/default/image.jpg';
//}
echo " <a href='feed.php?pid=" . $info['post_id'] . " ' >
<div style='background:#FFF5C3'> <br> <h2> " . $info['person_mentioned'] . " </h2>
<h3 style='color: black'> " . $info['body'] . " </h3> </div> </a>";
echo " <img src='" . $photoFileName . "' width='285px' height='200px' style='border: 5px solid black'>";
}
Related
I have encountered a small problem when trying to make my website more advanced. To put it simple:
when I wanted to display images in a table using Lightbox and PHP everyting worked well:
<tr>
<td class="w-25">
<a href="telewizory/telewizor1.jpeg" data-toggle="lightbox" data-lightbox="telewizor1" class="col-sm-4" >
<img src="telewizory/telewizor1.jpeg" class="img-fluid img-thumbnail" alt="Sheep">
</td>
<td>Philips 70PUS6704/12</td>
<td>3999</td>
</tr>
The first column presented the image, the second - name and the last one - price.
how it works
However, when I wanted to add MySQL and created a database in PHPMyAdmin something went wrong. I can still read the name and the price well, but images don't show, I can only see the alternative text - Sheep in this example.
New code:
<?php
$kat_id = isset($_GET['kat_id']) ? (int)$_GET['kat_id'] : 1;
$sql = 'SELECT `img`, `nazwa` , `cena`
FROM `produkty`
WHERE `kategoria_id` = ' . $kat_id .
' ORDER BY `nazwa`';
$wynik = mysqli_query($polaczenie, $sql);
if (mysqli_num_rows($wynik) > 0) {
while ($produkt = #mysqli_fetch_array($wynik)) {
echo
'<tr>
<td class="w-25">
<a href="telewizory/' . $produkt['img'] . ' data-toggle="lightbox" data-lightbox="' . substr($produkt['img'], 0, strpos($produkt['img'], ".")) . '" class="col-sm-4">
<img src="telewizory/' . $produkt['img'] . ' class="img-fluid img-thumbnail" alt="Sheep">'
. ' </td>
<td>' . $produkt['nazwa'] . '</td>'
. '<td>' . $produkt['cena'] . '</td>
</tr>'
. PHP_EOL;
}
} else {
echo 'wyników 0';
}
mysqli_close($polaczenie);
?>
how it doesn't work
I have no idea what may be the reason that this code doesn't work. I would be very grateful for any help :)
You should check that the $produkt['img'] here
<img src="telewizory/' . $produkt['img'] . ' class="img-fluid img-thumbnail" alt="Sheep">'
. ' </td>
is replaced with the expected value from the DB.
I have problem with displaying photo from database on the page. I made a path in database column image_src = "../GameForest/gamephoto/gta5.jpg". And path is correct I checked it several times.
//This is a class that displaying all the data from the database
<?php
class Game extends Dbh {
public function gameDiv() {
$id = $_GET['id'];
$stmt = $this->connect()->query("SELECT g.game_id, g.game_name, g.image_src, g.genre_id, g.developer_id, g.release_date, g.platfrom_id, g.game_price, g.game_description, g.processor, g.graphic, g.ram\n" . "FROM game AS g\n" . "LEFT JOIN genre AS z\n" . "ON g.genre_id = z.id WHERE game_id = '$id'");
while ($row = $stmt->fetch()) {
echo "<div class='gameName'><h2>" . $row['game_name'] . "</h2></div>";
echo "<div class='buying'><p>" . $row['game_price'] . "€</p><a href='bought.php'><button>Buy Game</button></a></div>";
//This next echo is for displaying photo from database:
echo "<div class='gamePhoto'><img>" . $row['image_src'] . "</img></div>";
echo "<div class='gameGenre'><b>Genre: </b><p>" . $row['genre_id'] . "</p></div>";
echo "<div class='gameDeveloper'><b>Created by: </b><p>" . $row['developer_id'] . "</p></div>";
echo "<div class='gamePlatform'><b>Platform: </b><p>" . $row['platfrom_id'] . "</p></div>";
echo "<div class='gameRdate'><b>Release date: </b><p>" . $row['release_date'] . "</p></div>";
echo "<div class='gameDescription'><b>Description: </b><p>" . $row['game_description'] . "</p></div>";
echo "<div class='sysRequirements'><p>Recommended System Requirements:</p><b>Processor:</b><p>" . $row['processor'] . "</p>" . " Heading <b>Graphic:</b><p>" . $row['graphic'] . "</p>" . " <b>RAM:</b><p>" . $row['ram'] . "</p>";
}
}
}
**//This is instance for previous class:**
<?php
#istance for printing information about a Game
$game = new Game;
echo $game->gameDiv();
?>
**//This is CSS code of that photo:**
.gamePhoto {
margin: 10px 0 20px 10%;
width: 200px;
height: 400px;
float: left;
}
.gamePhoto img {
width: 500px;
height: 600px;
}
?>
I expect that there is a picture from database but I get only a gray frame where the image should actually be below that it writes "../GameForest/gamephoto/gta5.jpg" (the path I wrote in the base).
The rest of the database data are displayed normally it's just a problem with images.
On the other page (and other class) the same picture from the same database is normally displayed and I have no problem.
img is inline block,use it like <img src="" />
Change this
<img>" . $row['image_src'] . "</img>
to this
<img src=" . $row['image_src'] . ">
I have been trying to set up a page that lists prices of items from a table in a database. Here is my code:
<?php
$querylist = mysql_query("SELECT item_name,image,price,added_by FROM values");
while($row = mysql_fetch_array($querylist))
{
echo '<div class="post rareitem" style="margin-right: 15px;float: left;">
<div class="rarename">
<strong>';
// Shows Item Name
echo $row['item_name'];
echo '</strong>
</div>';
// Shows Item Image
echo '<div class="rareimage" style="background-image: url(/app/tpl/skins/Mango/images/values/rares/';
echo $row['image'];
echo ');"></div>';
// Shows Item Price
echo '<div class="rarecontrols">
<div class="coinsbox"></div>
<span>
<b> <b>Credits: </b> </b> ';
echo $row['price'];
echo '</span>';
// Shows Who Added the Item
echo '<div class="addedbox"></div><b><b><span><font color="#c93734"><font color="#c93734">Added By: </font> </font>';
echo $row['added_by'];
echo '</span></b></b>
</div>
<div class="clear"></div>
</div>';
}
?>
There is another chunk of code (shown below) that I have based this off of, and it works perfectly fine. I can't seem to get this to work though. I believe it has something to do with the SQL, the syntax, or something. No matter what I do, it produces absolutely no results, yet the code below results exactly as planned. I know for a fact it is not a connection issue because the below code can be placed on the same exact page as the above one and it works fine, however the above does not.
<?php
$querylist = mysql_query("SELECT id,username,motto,country,look,rank,account_created,role,account_created,online,last_online FROM users WHERE rank='9' ORDER BY ID LIMIT 20");
while($row = mysql_fetch_array($querylist))
{
echo '
<div class="team">';
// Showing Avatar
echo '<div style="float: left; margin-top:-1px;height: 60px; width: 64px; background: url(http://www.habbo.nl/habbo-imaging/avatarimage?figure=';
echo $row['look'];echo "&action=wav&direction=3&head_direction=3&gesture=sml&size=m) no-repeat 0px -10px";
echo "\"/>";
echo "<img alt=\"badge\" src=\"/app/tpl/skins/habbo/images/icons/";
echo $row['online'];echo ".gif\"></div>";
// Flags
echo "<br/><img src=\"/app/tpl/skins/habbo/images/icons/flags/";
echo $row['country'];echo ".png";
echo '" style="float:right;" /> <b><uf>';
echo $row['username'];echo "</u></b>";
// Bans & Ticket Count
$Bans = mysql_query("SELECT * FROM `bans` WHERE `added_by` = '" . $row['username'] . "'");
$BanCount = mysql_num_rows($Bans);
$Tickets = mysql_query("SELECT * FROM `moderation_tickets` WHERE `moderator_id` = '" . $row['id'] . "'");
$TicketCount = mysql_num_rows($Tickets);
//Role
echo "<br/><gb>Role: </b><fi> ";
echo $row['role'];echo "";
echo "</i>";
// Echoing bans & Tickets
echo "<br/><gb>Bans: </b><fi> ";
; echo $BanCount;
echo "</i>";
echo " <gb>Tickets: </b><if>";
; echo $TicketCount;
echo "</i>";
echo "</div>";
}
?>
Thanks in advanced, any assistance will be greatly appreciated!
values is Reserved Words in mysql it should be on backtick
SELECT item_name,image,price,added_by FROM `values`
And stop using mysql it is deprecated. Instead use mysqli or PDO
I'm new to php. Does not know how to use with expressions.
Here is a php code from search file of my site.
I want add html tags such as href, div, li, ul, etc. How could i do it?
if(mysqli_num_rows($results) >= 1)
{
$output = "";
while($row = mysqli_fetch_array($results))
{
$output .= "Size: " . $row['fh_Vsize']. "<br />";
$output .= "Icon: <img src=" . $path .$row['fh_Sicon']. " alt=><br />";
$output .= "File ID: " . str_replace("_"," ",$row['fh_Sid']) . ""; $nbsp; $nbsp; $output .= "" . $row['fh_Vcaption'] . "<br />";
$output .= "Description: " . substr(strip_tags($row['fh_Sdescription']),0,150) . "<br />";
$output .= "Download: <a href=download_" . $row['fh_Sid'] . "/>Download</a><br /><br />";
}
echo $output;
}
else
echo "There was no matching record for the name " . $searchlink;
Something like this. I'm sorry for this code. I'm new here and will learn the basics:
<div class="info">
<h4>'.de_string($rec['fh_Sid']) .' ' .$rec['fh_Vcaption'] .' '. $rec['fh_Vextension']. '<span class="updated">updated</span></h4>
<div><img style="float:left;margin-right:5px" src="'. $path . str_replace("t_", "",$rec['fh_Sicon'] ).'"/></div><p>'. substr (strip_tags($rec['fh_Sdescription']),0,170) .' ...</p>
<ul class="prod-info">
<li class="none-separator">Last update: <strong>' . strftime("%d %b %Y", $rec['fh_Vdate']) . '</strong></li>
<li>License: '. $rec['fh_Vlicense'] . '</li>
<li>Size: <strong>'.$rec['fh_Vsize'].'</strong></li>
<li>Downloads: <strong>'. $views[$sid] .'</strong></li>
<li><img src="../../images/dl.png"/> Download</li>
</ul>
</div>
I am sorry this is not a full code
but basically you can use something like this
while ($line1 = mysqli_fetch_object($result2))
{
$i=0;
$id = $line1->$index; // fetching the whole object id of the SQL table
foreach ($line1 as $value1)
{
list($idName,$ext) = explode(".",$value1);
if ($i==1) // to show only the icon name
{
echo '
<li id='.$value1.' name="'.$id.'">
<form id="addchart'.$idName.'" action="addchart.php" target = "_self" method="post">
<a id='.$idName.' onmousedown = "AddorDelete(this.id,this.value)" href = "#" value='.$idName.'>
<img id="picture" class="icon" src="images/item/php.png" width="70" style="margin: 0px 0px 0px 0px"/>
<input type="hidden" name="db" value="'.$db.'" />
<input type="hidden" name="table" value="'.$table.'" />
<input type="hidden" name="id" value="'.$id.'" />
You could just echo 'html code and the attribute here'
be careful of the syntax to assign value, name or id if you want to assign the value, name or id with the predefined PHP variable you have made.
I prefer this way, which will let you have both php and html in their own format and easy to update:
<?php
if(mysqli_num_rows($results) >= 1)
{
while($row = mysqli_fetch_array($results))
{
?>
<div class="info">
<h4><?=de_string($rec['fh_Sid']) .' ' .$rec['fh_Vcaption'] .' '. $rec['fh_Vextension']?><span class="updated">updated</span></h4>
<div><img style="float:left;margin-right:5px" src="<?=$path . str_replace("t_", "",$rec['fh_Sicon'] )?>"/></div><p><?=substr (strip_tags($rec['fh_Sdescription']),0,170)?> ...</p>
<ul class="prod-info">
<li class="none-separator">Last update: <strong><?=strftime("%d %b %Y", $rec['fh_Vdate'])?></strong></li>
<li>License: <?=$rec['fh_Vlicense']?></li>
<li>Size: <strong><?=$rec['fh_Vsize']?></strong></li>
<li>Downloads: <strong><?=$views[$sid]?></strong></li>
<li><img src="../../images/dl.png"/> Download</li>
</ul>
</div>
<?php
}
}
else
echo "There was no matching record for the name " . $searchlink;
?>
I'm having problems with showing data from a selected row into another div.
Meaning I'm showing eg forename and lastname, when the user clicks on the name (as a link), I would like to show more data from the Id chosen, and I would like it to be shown in a div box below.
See the site here: http://kristoff.it/onlinecoaching/
And my code:
<div class="greenBox1">
<h1>1 - VÆLG DIN ONLINE COACH</h1>
<div class="whiteBox1">
<?php
$sql = "SELECT * FROM coach ";
$coachId = $row["coachId"];
$fornavn = $row["fornavn"];
$efternavn = $row["efternavn"];
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
{
echo '<table border="0" align="left" height="100">';
echo '<tr>';
echo '<td width="95" rowspan="2" align="center" valign="middle"><img src="' . $row['imgUrl'] . '" width="85" height="85" alt="' . $row['imgAlt'] . '"/>' . '</td>';
?>
<!-- here I'm trying to write the id of the selected name to the div box below -->
<?
echo '<td><h2>' . $row['fornavn'] . $row['efternavn'] . '</h2></td>';
echo '</tr>';
echo '<tr>';
echo '<td valign="top" width="190"><p>' . $row['beskrivKort'] . '<br></p></td>';
echo '</tr>';
echo '</table>';
}
?>
</div>
</div>
<div class="greenBox2">
<h1>2 - BOOK TID I COACHENS KALENDER</h1>
<div class="whiteBox2" id="whiteBox2">
<!-- here would like the more data to show -->
</div>
</div>
Regards Maria
In your website, your URLs are empty. You need to put your ID.
echo '<td><h2>' . $row['fornavn'] . $row['efternavn'] . '</h2></td>';
With that URL, you will send the ID as a GET variable.
You must then request your data if the ID is set.
<div class="whiteBox2" id="whiteBox2">
<?php
if (isset($_GET['id']))
{
$sql = "SELECT * FROM coach WHERE coachId=" . (int)$_GET['id'];
// Do your stuff...
echo "Hello";
}
?>
<!-- here would like the more data to show -->
</div>