Display image from database as background of a div element in php - php

Currently I'm learning about PHP and database, I wrote the script below to display the image as background for my div element, but the output is actually nothing! the error is from the line:
echo "<div class=\"post\" style='background-image: url('\"<?php echo $data[Image];\"?>')'";?>
The quotes mess up! Can someone tell me how to correct this? I tried to change double quotes to single quotes, but still doesn't work at all.
This is my full script:
<div class="dashboardA">
<?php
$con = mysqli_connect("localhost", "Dave", "password");
if (!$con){
die ("Could not connect to database: " . mysqli_connect_error());
}
mysqli_select_db($con, "my_blog");
$sql = mysqli_query($con, "select * from article");
while ($data=mysqli_fetch_array($sql)){
echo "<div class=\"post\" style='background-image: url('\"<?php echo $data[Image];\"?>')'";?>
<?php echo "<p>" . $data["Title"] . "</p>";
echo "<p>" . $data["Category"] . "</p>";
echo "<p>" . $data["Published"] . "</p>";
echo "</div>";
}
?>
</div>

You are getting a little mixed up. You already have PHP opening tags, you don't need them again. Just concatenate your variable:
echo "<div class='post' style='background-image: url(\"$data[Image]\")'>";
Note: You also need to close your opening <div> tag.

There is a mistake in the line
echo "<div class=\"post\" style='background-image: url('\"<?php echo $data[Image];\"?>')'";?>
You are already in php, so the opening tags are wrong there.
Try:
echo "<div class=\"post\" style='background-image: url(\"" . $data[Image] . "\")'";?>

Try this
while ($data=mysqli_fetch_array($sql)){
echo "<div class=\"post\" style='background-image: url('\"<?php echo $data[Image];\"?>')'";?>
<?php echo "<p>" . $data["Title"] . "</p>";
echo "<p>" . $data["Category"] . "</p>";
echo "<p>" . $data["Published"] . "</p>";
echo "</div>";
}
Replace this
with this
while ($data=mysqli_fetch_array($sql)){
$img = $data["Image"];?>
<div class="post" style="background-image: url('<?php echo $img;?>')" >
<?php echo "<p>" . $data["Title"] . "</p>";
echo "<p>" . $data["Category"] . "</p>";
echo "<p>" . $data["Published"] . "</p>";
echo "</div>";
}

You actually did it right in the following echo commands. To combine the value of your variable and a string you use the "." that basically substitutes for "+" that is used in other languages for this purpose. Opening a new php tag is therefore not needed here.
The correct code is
echo '<div class="post" style="background-image: url(\'' . $data[Image] . '\')">';

Try this, outside php tags.
<div class="post" style="background-image: url('<?php echo "$data[Image]"; ?>');">

Related

SQL query not returning array

Working on getting a page to build off of an array that is returned from a DB to post a story, not sure what it is not working. The page URL looks like this: https://ohcrap.ninja/games/ps4/article.php?id=1
Here is the code that should be generating the content:
<?php
$id = $_GET['id'];
$query = mysqli_query($con,'SELECT * FROM `PS4` WHERE `id` =' .$id) or die(mysqli_error($con));
while ($row = mysqli_fetch_array($query));
// Echo page content
echo "<div class='col s12 m12 l12'>";
echo "<div class='card small grey darken-3'>";
echo "<div class='card-stacked'>";
echo "<div class='card-content'>";
echo "$id";
echo "<span class='card-title'>" . $row['title'] . "</span>";
echo "<hr color='black'>";
echo "<P>By:<i> " . $row['author'] . "</i></P>";
echo "<P>Published: " . $row['published'] . "</P>";
echo "<br>";
echo "<P class='truncate'>" . $row['story'] . "</P>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
?>
Your while loop is not doing anything useful, because you're immediately ending it with that ;.
while ($row = mysqli_fetch_array($query)) {
// all those echoes
}

foreach loop in while loop with div inside list element

hello guys i am trying to make a foreach loop in a while loop. in foreach loop i try to produce list elements with divs inside them but i have very strange output
here is my code
$countercat= 0;
$classvar= 1;
echo "<div class='selector-page'>";
echo "<div class='selector'>";
echo "<ul>";
while ($countercat <= 8){
$stmt=$conn->prepare('SELECT eidos, name, meta_keys, address, telephone, perioxi, st_img, st_open, st_close, lat, longtit FROM magazia WHERE perioxi= :perioxi AND eidos= :eidos ORDER BY st_id ASC');
$stmt->bindParam(':perioxi', $name, PDO::PARAM_STR);
$stmt->bindParam(':eidos', $eidos, PDO::PARAM_STR);
$eidos= $c_titles[$countercat]['c_name'];
$stmt->execute();
$allrows=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($allrows as $row) {
echo "<li>";
echo "<div class='p". $classvar . " w3-card targetDiv w3-margin-top cardsmar'>";
echo "<img src='../uploads/" . $row['st_img'] . "' class='cccard' alt='" . $row['name'] . "'";
echo "<div class='w3-container w3-center'>";
echo "<h3>" . $row['name'] ."</h3>";
echo "<p>" . $row['eidos'] . "</p>";
echo "<p>" . $row['address'] . " , " . $row['perioxi'] . "</p>";
echo "<p>" . $lang['wrlt'] . " : " . $row['st_open'] . "-" . $row['st_close'] . "</p>";
echo "<a href='katastimata.php?name=" . $row['name'] . "' role='button' class='w3-button w3-round w3black'>" . $lang['t9'] . "</a><br />";
echo "<a href='https://www.google.com/maps?q=loc:" . $row['lat'] . "," . $row['longtit'] . "' role='button' class='w3-button w3-round w3-green btnmar'>" . $lang['spot2'] . "</a>";
echo "</div>";
echo "</div>";
echo "</li>";
}
$countercat++;
$classvar++;
}
echo "</ul>";
echo "</div>";
echo "</div>";
}
?>
here is an image from my debugger consonle
as you see in the image inside in the ul tag exists only one li elemenemt
and the rest of them are out side ul /ul.
my first thought was that is not valid to put div tag in a li tag but this is not true if i use this in the top of my file
DOCTYPE html PUBLIC "-//W3C// DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/html1-transitional.dtd"
html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang:"en"
i am stack here for so long
what am i missing guys?
thanks in advance
vaggelis
You Didn't Close the <img> tag here.
echo "<img src='../uploads/" . $row['st_img'] . "' class='cccard' alt='" . $row['name'] . "'";
You Must Close the tag as
echo "<img src='../uploads/" . $row['st_img'] . "' class='cccard' alt='" . $row['name'] . "'/>";

Put contents of PHP while loop code within a DIV

So I want to apply this DIV class to these PHP items.
This is what I have, I know it does not work, but what would be correct for what I am trying to achieve.
I cant add the class to each individually, as I want the entire contents to be within the one div.
Hope that makes sense, thanks!
<?php
while($campaigns= mysqli_fetch_assoc($result)){
<div class="feeditem">;
echo "<div class='field'>".$test['part0']."</div>";
echo "<div class='field'>".$test['part1']."</div>";
echo "<div class='field'>".$test['part2']."</div>";
echo "<div class='field'>".$test['part3']."</div>";
echo "<div class='field'>".$test['part4']."</div>";
echo "<div class='field'>".$test['part5']."</div>";
echo "<div class='field'>".$test['part6']."</div>";
</div>;
}
?>
You should use an IDE that gives you errors for syntax problems... You do not have all the html code wrapped in echo ""; statements.
while ($campaigns = mysqli_fetch_assoc($result)) {
echo '<div class="feeditem">';
echo "<div class='field'>" . $test['part0'] . "</div>";
echo "<div class='field'>" . $test['part1'] . "</div>";
echo "<div class='field'>" . $test['part2'] . "</div>";
echo "<div class='field'>" . $test['part3'] . "</div>";
echo "<div class='field'>" . $test['part4'] . "</div>";
echo "<div class='field'>" . $test['part5'] . "</div>";
echo "<div class='field'>" . $test['part6'] . "</div>";
echo '</div>';
}
I believe this is what you're trying to accomplish:
<?php
echo '<div class="feeditem">';
while($campaigns = mysqli_fetch_assoc($result)){
echo"<div class='field'>".$test['part0']."</div>";
echo"<div class='field'>".$test['part1']."</div>";
echo"<div class='field'>".$test['part2']."</div>";
echo"<div class='field'>".$test['part3']."</div>";
echo"<div class='field'>".$test['part4']."</div>";
echo"<div class='field'>".$test['part5']."</div>";
echo"<div class='field'>".$test['part6']."</div>";
}
echo '</div>';

Using php code in html to list images

I'm using this code :
<?php
// Grab the data from our people table
$sql = "select * from people";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<br><br><br><br>";
echo $row['fname'] . " " . $row['lname'] . "<br />";
echo "<img class=\"picture2\" src=\"images/" . $row['filename'] . "\" alt=\"\" /><br />";
echo "</p>";
}?>
to list some images that have been saved by name in the database ... but when I want to put them in a table (using bootstrap components), it doesn't show any images ... my code is :
<div class="row">
<div class="col-md-6">
<?
while ($row = mysql_fetch_assoc($result))
{
echo $row['fname'] . " " . $row['lname'] . "<br />";
echo "<img class=\"img-rounded\" src=\"images/" .$row['filename'] . "\" alt=\"\" /> <br />";
echo "</p>";
}?>
</div>
</div>
Do you have any clue what i've to do to list images in the table ?
and my second question is how can I list images in just two columns ? it's not important how many rows does it take to show images but i want it to show two images in a line (but in two separated cells) ...

Is there a better or more efficient way to do this?

This code is working for what I need it to do, but (in my opinion) it looks bad so I am hoping someone knows of a cleaner or more efficient way to do the same thing. I have several entries being pulled from the database and I want them to be styled identically. Only the logo and the the link name will change eventually I will add a description. Here is the code:
<div class="content">
<?PHP
while($row = $stmt->fetch())
{
$name = $row['name'];
$id = $row['id'];
$logo = $row['logo'];
$username = $row['username'];
echo "<div class=" . "Links" . ">";
echo "<div class=" . "linkImages" . ">";
echo "<br>" . "" . "<img src=" . "users/" . $username . "/images/" . $logo . " " . "width=" . "200" . " " . "height=" . "auto" . " " . "border=" . "0" . "/>" . "";
echo "</div>";
echo "<div class=" . "linkName" . ">";
echo "" . $name ."";
echo "</div>";
echo "</div>";
}
?>
</div>
You can trivially remove most of the echoes and string concatenation by switching to a HEREDOC:
while($row = $stmt->fetch()) {
echo <<<EOL
<div class="links">
yadayada
<br><a href="Profile.php?id={$row['id']}"><img src="users/{$row['username']}" etc....
yada yada yada
EOL;
Note that the lack of escapes in there, allowing for proper quotes around the tag attributes, and the {} notation on the embedded variables.
Don't use extra variable names. Instead, use the original.
Also, don't output every row with PHP. Use plain HTML and add the variable in it later:
<div class="Links">
<?=$row['name']?>
Or just echo as 1 line, no need for concatenation
echo "<div class=\"linkImages\">";
or
echo '<div class="linkImages">';
echo '<div class="content">';
while($row = $stmt->fetch()){
$name = $row['name'];
$id = $row['id'];
$logo = $row['logo'];
$username = $row['username'];
echo '<div class="Links">
<div class="linkImages">
<br><img src="users/'.$username.'/images/'. $logo .'" width="200" height="auto" border="0">
</div>
<div class="linkName">
'.$name.'
</div>
</div>';
}
echo '</div>';
Here's how I would write it:
<div class="content">
<?php
while ($row = $stmt->fetch()){
echo '<div class="Links">';
echo '<div class="linkImages">';
echo '<br /><img src="users/'. $row['username'] .'/images/'. $row['logo'] .'" width="200" />';
echo '</div>';
echo '<div class="linkName">';
echo ''. $row['name'] .'';
echo '</div>';
}
?>
</div>
Note that I removed the border="0" for the img tag - that should be done with CSS.
The short answer is yes. There is almost always a cleaner or more efficient way to do it.
How about something like this?
<div class="content">
<?PHP while($row = $stmt->fetch()) { ?>
<div class="Links">
<div class="linkImages">
<br><img src="users/<?=$row['username'] ?>/images/<?=$row['logo'] ?> width="200" height="auto" border="0" />
</div>
<div class="linkName">
<a href="Profile.php?id="<?=$row['id'] ?>><?=$row['name'] ?></a>
</div>
</div>
<?PHP } ?>
</div>
There are a lot of erroneous symbols etc in this, it comes with practice, but something like this might be worth trying
<?php
while($row = $stmt->fetch()) {
$string = "";
$string .= "<div class=\"Links\">\n";
$string .= "<div class=\"linkImages\">\n";
$string .= "<br />\n";
$string .= "<img src=\"users/". $row['name'] ."/images/" . $row['logo'] . "\" width=\"200\" height=\"auto\" border=\"0\" />\n";
$string .= "</div>\n";
$string .= "<div class=\"linkName\">\n";
$string .= "". $row['name'] ."\n";
$string .= "</div>\n";
$string .= "</div>\n";
echo $string;
}
?>
I'd recommend learning how to use the printf() family of functions.
$frame = '<img src="users/%s/images/%s" width="200" height="auto" border="0"/>';
printf($frame, $id, $username, $logo);

Categories