HTML inside PHP not working - php

I have been trying to put HTML inside PHP for a while, but I could never get it to work. Instead I have had to use this
<?php //code in here
while($record = mysql_fetch_array($myData)){
?>
//HTML code
<?php
}
?>
and it has worked for a while, but now I'm implementing a search function to the page, and I need all HTML to be dynamically generated, or the page will be displayed twice. Therefore, i'm in need of some help. This is the old-new code I have at the moment.
<?php
$sql = "SELECT * FROM `LISTINGS` ORDER BY YA DESC $limit";
$myData = mysql_query($sql,$con);
while($record = mysql_fetch_array($myData)){
//this is what i have manage to get done
echo '<div class="cards-row">';
echo '<div class="card-row">';
echo '<div class="card-row-inner">';
echo '<div class="card-row-image" data-background-image="http://domains/$record["IMAGENAME"].jpg">';
echo '</div>';
echo '<div class="card-row-body">';
echo '<h2 class="card-row-title">';
echo '<a href="http://domain/listing-detail.php?ID='; $record['ID']echo'">'
echo '</a>';
echo '</h2>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
?>
Static/dynamic code
<div class="card-row">
<div class="card-row-inner">
<div class="card-row-image" data-background-image="http://www.domain/<?php echo $record['IMAGENAME'];?>.jpg" width="150" height="180" ">
</div><!-- /.card-row-image -->
<div class="card-row-body">
<h2 class="card-row-title">
<a href="http://www.domain/listing-detail.php?ID=<?php echo $record['ID'];?>"> <?php custom_echo ($record['TITLE'], 80); ?><?php if($record['STREET']===' '){ echo "Not provided" ;}?>
</a>
</h2>
<div class="card-row-content"><?php custom_echo ($record['DESCRIPTION'], 250); ?><?php if($record['STREET']===' '){ echo "Not provided" ;}?></div><!-- /.card-row-content -->
</div><!-- /.card-row-body -->
<div class="card-row-properties">
<dl>
<dd></dd><dt>Visit Website</dt>
<dd></dd><dt>More Info</dt>
<dd>Added</dd><dt><?php echo $record['YA'];?>/<?php echo $record['MU'];?>/<?php echo $record['DU'];?></dt>
<dd>Viewed</dd><dt>Visited</dt>
</dl>
</div><!-- /.card-row-properties -->
</div><!-- /.card-row-inner -->
</div><!-- /.card-row -->
</div><!-- /.cards-row -->
<br/>
<?php
}
?>
My goal is to put all the code above inside
while($record = mysql_fetch_array($myData)){

Although this is not the best way when it comes to readability and maintainability, the way I usually process HTML with PHP is by echoing it.
echo "<div style=\"color:red\">test</div>";
If I need to add PHP content then
$myVar = "test";
echo "<div style=\"color:red\">" . $myVar . "</div>";
And if I already have some HTML code I'd like to escape, I can easily do so using Notepad++'s replace all function by replacing " with \"

You have an error in line 15
echo '<a href="http://domain/listing-detail.php?ID='; $record['ID']echo'">'
Change it to:
echo '<a href="http://domain/listing-detail.php?ID='.$record['ID'].'">';
Also, are you saving it in ".php" extension?.
After the last echo, you forget a '}'.
Finally, remove your mysql_ function and use mysqli_ or PDO, if you're on PHP7.

Related

Returning SQL data within an image tag using PHP

When I run the following file I get the database data i.e it prints it out on the website so I know my connections are good.
<html>
<?php include 'config.php'?>
<?php include 'header.php'?>
<?php
$sql = "SELECT name, image FROM images";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo $row["name"], $row["image"];
}
?>
</div>
</html>
However when I try and format the results like below
<html>
<?php include 'config.php'?>
<?php include 'header.php'?>
<?php
$sql = "SELECT name, image FROM images";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo <div id = "bookbar">
<img src= "$row['image']" alt = "image">
<p> $row['name'] </p>
</div>
}
?>
</div>
</html>
it doesn't work. Can anyone help me fix the code?
Maybe try this your code didn't close/open the php tags properly also don't echo like that
<?php include 'config.php'?>
<?php include 'header.php'?>
<?php
$sql = "SELECT name, image FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<div id = "bookbar">
<img src= "<?php echo $row['image'] ?>" alt = "image">
<p><?php echo $row['name']; ?></p>
</div>
<?php
}
}
$conn->close();
?>
If you want to echo something out
Its better to close on open the php tags like so
PHP goes here
?>
HTML goes here
<?php
PHP goes here
And if you want to echo something inside the HTML just do this
<span> <?php echo "something" ?> </span>
much easier and makes the code easier to read.
change your echo statement to -
echo '<div id = "bookbar"><img src= "' . $row['image'] . '" alt = "image"><p>'. $row['name'] .'</p>'
Your issue is a syntax problem - you can't use echo like that, it has to echo a string variable. You should be seeing an error message about it.
You could keep the echo statement and put all the HTML inside a string, and concatenate (or interpolate) the PHP data into it. But IMO the easiest thing here in terms of readability and maintenance is to step out of the PHP tags, print the HTML, embed some PHP tags in it for the variables, and then step back in again to continue with the code. It makes the HTML far easier to understand:
?>
<div id="bookbar">
<img src="<?php echo $row['image'] ?>" alt="image">
<p><?php echo $row['name'] ?></p>
</div>
<?php
When you are in php mode you should echo strings as php variables wrapped with single quotes:
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo '<div id = "bookbar">';
echo '<img src="' . $row['image'] . '" alt = "image">';
echo '<p>' . $row['name'] . '</p>';
echo '</div>';
}

target='_blank' not working in any browser

Below is my code for downloading some files from a webpage.
Everything works fine except target="_blank". This button does nothing even though the link is correct. If I right click and press open in a new tab it works but when i press the button it does nothing.
<?php
while ($row = $result->fetch_assoc()) {
$i+=1;
$name = $row["filename"];
$location = "../uploadedfiles/" . $name;
?>
<div class="row">
<p><hr>Name : <?php echo $row["name"] ?> <br> Contact Details : <?php echo $row["number"] ?><br></p>
</div>
<div class="row">
<p>Date Sent: <?php echo date("F d Y-- H:i:s.", filectime($location)) ?><br></p>
</div>
<div class="row">
<p><p> <?php echo $i ?> ) <?php echo substr($name, 10) ?> <a href="../uploadedfiles/<?php echo $name; ?>" target='_blank'><button type='button' class='btn btn-info'>View / Download </button></a></p></p>
</div>
<?php }
?>
<hr>
<?php
} else {
echo "0 results";
}
$con->close();
The way you have created button within the anchor tag is not one of the best practices to be followed.
Ideally you should do something like this:
View/Download
Hope this helps.

Html link <a> not wrapping <div> element properly

I am currently writing a php website where I encountered a problem where the html link will not wrap div element properly. I have not found an answer to my problem yet, so I appreciate if someone can help me.
This is the php code I had written:
ECHO '<a target="_blank" href="' . $row["link"] . '">';
ECHO '<div class="header-box">';
ECHO '<div class="detail">';
ECHO '<p class="title">' . $row["title"] . '</p>';
$user_data = get_user_data($row["owner_id"]);
ECHO '<p class="author">This article is shared by <a class="user" href="./member.php?action=profile&id='.$user_data["id"].'">' . $user_data["firstname"] . " " . $user_data["lastname"] . '</a> on '.date("d F Y", strtotime($row["posted"])).'.</p>';
ECHO '</div>';
ECHO '<div class="good">';
ECHO '<p id="number">'.$row["good"].'</p>';
ECHO '<p id="icon"><i class="fa fa-thumbs-o-up"></i>Useful</p>';
ECHO '</div>';
ECHO '<div class="bad">';
ECHO '<p id="number">'.$row["bad"].'</p>';
ECHO '<p id="icon"><i class="fa fa-thumbs-o-down"></i>Not Useful</p>';
ECHO '</div>';
ECHO '</div>';
ECHO '</a>';
However, the outcome of the php code in browser are as followed:
<div class="header-box">
<a target="_blank" href="http://designinstruct.com/tools-basics/5-easy-steps-optimize-your-images-photoshop/"></a>
<div class="detail">
<a target="_blank" href="http://designinstruct.com/tools-basics/5-easy-steps-optimize-your-images-photoshop/">
<p class="title">5 Easy Steps to Optimize Your Images in Photoshop</p>
</a>
<p class="author"><a target="_blank" href="http://designinstruct.com/tools-basics/5-easy-steps-optimize-your-images-photoshop/">This article is shared by </a><a class="user" href="./member.php?action=profile&id=2">demoname demo</a> on 01 January 1970.</p>
</div>
<div class="good"><p id="number">1</p><p id="icon"><i class="fa fa-thumbs-o-up"></i>Useful</p></div>
<div class="bad"><p id="number">2333</p><p id="icon"><i class="fa fa-thumbs-o-down"></i>Not Useful</p>
</div></div>
I am getting a little bit frustrated trying to fix the problem because I can't figure out what is going wrong? The other part of code written with html link wrapping the div are working fine. Can anyone help me out? Thanks.
So the question was solved by Rick Hitchcock for pointing out my nesting issue.
So the answer is not nesting an tag within another tag.
After seeing the refactored code, I realized you have a link inside another link. The browser doesn't know what to do with this, so it closes them both down as small as they can.
Try using html inside your .php file, and just using tags where you have to use php. For Example:
close the php with a ?>, then open it each time you need it by wrapping your code in
<?php //php code goes here ?>
Here's your code refactored:
<a target="_blank" href="<?php echo $row["link"] ?>">
<div class="header-box">
<div class="detail">
<p class="title"><?php echo $row["title"] ?></p>
<?php $user_data = get_user_data($row["owner_id"]); ?>
<p class="author">This article is shared by <a class="user" href="./member.php?action=profile&id=<?php echo $user_data["id"] ?>"><?php echo $user_data["firstname"] ?> <?php echo $user_data["lastname"] ?></a> on <?php echo date("d F Y", strtotime($row["posted"])) ?></p>
</div>
<div class="good">
<p id="number"><?php echo $row["good"] ?></p>
<p id="icon"><i class="fa fa-thumbs-o-up"></i>Useful</p>
</div>
<div class="bad">
<p id="number"><?php echo $row["bad"] ?></p>
<p id="icon"><i class="fa fa-thumbs-o-down"></i>Not Useful</p>
</div>
</div>
</a>
Why are you using pure PHP for this? Its not necessary?

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

Data from database show/hide onclick trouble

<?php
$getNews = $db->prepare("SELECT * FROM news ORDER BY id DESC LIMIT 4");
$getNews->execute();
$news = $getNews->fetchAll();
foreach ($news as $newspost) {
echo $newspost['title'] ; ?> <a style="cursor:pointer;" onclick="return toggleMe('problem')">read/hide</a>
<?php
echo '<br />';
echo 'Posted by '; echo $newspost["user"]; echo ' at '; echo $newspost["created"]; ?>
<div id="<?php echo $newspost['id']; ?>" style="display:none;">
<?php
echo $newspost['message'];
?>
</div>
<?php
echo '<br /> <br />';
}
?>
What I had in mind was that it shows/hides the text from the newspost when you hit the read/hide link next to the title of the newspost.
I can fit the $newspost['id'] in the representing div but because the onclick="return toggleMe('problem')"> has both " and ' in it I need another way to fit it in there, I searched a lot but couldn't find what I was exactly looking for.
Actually, you'll be fine with:
"return toggleMe('<?php echo $newspost['id']; ?>');"
The inner single quotes will never be seen in the output HTML, and the <?php ?> block doesn't care what quotes surround it.

Categories