PHP if statement inside for loop and append result in divs - php

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?

Related

How to add php from database into individual html divs

I am creating a search, and what I want is when the user searches they will be able to see a number of different attractions appear. At the minute when I search the data appears in a long list.
else {
while ($row = mysqli_fetch_array($result)) {
$attraction_name = $row['attraction_name'];
$lat = $row['lat'];
$long = $row['long'];
$cost = $row['cost'];
$image = "<img src='{$row['image']}' height='100' width='100'>";
$output .= '<div>'.$attraction_name.' '.$lat.' '.$long.' '.$cost.' '.$image.'</div>';
}
}
I have added a simple html format which looks like the following
<div class="col-md-4">
<div class="thumbnail">
<?php print ("$output");?>
</div>
However the html appears all the time and I don't want this. What I would like is to create a search and then when the search results are returned they will appear in the html divs. Does anyone know how to do this? Thanks in advance.
You can wrap HTML in PHP logic like so:
<?php
if ($hasResults)
{ ?>
<div class="col-md-4">
<div class="thumbnail">
<?php print ("$output");?>
</div>
<?php }
?>

start PHP echo over every fourth mysql table row

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
}

Div tag doesn't close in php

Easy one! I'm trying to code a cheap forum. Coming from a C background, I started to noticed something strange about PHP. While having a function return a string (HTML) inside of a DIV into place, the browser would not print the </DIV> - even when it's echo'ed by itself.
Does PHP decide when it wants to echo certain DOM elements or have limitations on HTML output?
echo "Start<div id='Forum'>";
echo "Forum";
GetFullList();
echo "</div>";
Where, GetFullList() consists of:
function GetFullList(){
$sql="SELECT * FROM `Forum` WHERE `IsReply` =0";
$result=mysql_query($sql);
if (!$result){
echo mysql_error();
}
if($result){
while($ForumEntry = mysql_fetch_assoc($result)){
$IsReply = $ForumEntry["IsReply"];
$ParentPost = $ForumEntry["ParentTopic"];
$f_User = $ForumEntry["User"];
$f_Replies = $ForumEntry["Replies"];
$f_Views = $ForumEntry["Views"];
$f_Time = $ForumEntry["Time"];
$f_Post = $ForumEntry["Post"];
$f_Topic = $ForumEntry["Topic"];
$f_Index = $ForumEntry["Index"];
echo DisplayPost($f_User, $f_Replies, $f_Views, $f_Time, $f_Post, $f_Topic, $f_Index);
GetChildPostsOf($ParentPost);
}
}
}
And DisplayPost() is built as such:
function DisplayPost($f_User, $f_Replies, $f_Views, $f_Time, $f_Post, $f_Topic, $f_Index){
$PostBlock = "<div id='Grp_Cell' style='width:930;background-color:#999999;text-align:left;'><div id='Grp_Cell' style='float:left;'><div id='Tbl_Cel'>User: ".$f_User."</div><div id='Tbl_Cel'>Replies: ". $f_Replies."</div><div id='Tbl_Cel'>Views: ".$f_Views."</div><div id='Tbl_Cel'style='background-color:777777;height:112;'>Post started on ".$f_Time.". </div></div><div id='Grp_Cell' style='float:right;width:600;'><div id='Tbl_Cel'>Subject: ".$f_Topic."</div><div id='Tbl_Cel' style='background-color:777777;height:150;'>". $f_Post."</div><a onClick='Reply(".$f_Index.");Filter();'><div id='Tbl_Cel' style='background-color:#888888; height:50; width:50; float:right; padding:2;border-color:black; border:2;'><br>Reply</div></a></div>";
return $PostBlock;
}
(Displays a div scaffolding for DB results: the post.)
When I try to echo "< /div>" after GetFullList(), the result is not printed in HTML, leaving the rest of the page to be encompassed under the malformed div.
There are 10 opening divs and 9 closing divs in $PostBlock. A closing </div> should be added where necessary. An easy way to see what the output looks like is to break it into lines like this:
$PostBlock = "
<div id='Grp_Cell' style='width:930;background-color:#999999;text-align:left;'>
<div id='Grp_Cell' style='float:left;'>
<div id='Tbl_Cel'>User: ".$f_User."</div>
<div id='Tbl_Cel'>Replies: ". $f_Replies."</div>
<div id='Tbl_Cel'>Views: ".$f_Views."</div>
<div id='Tbl_Cel'style='background-color:777777;height:112;'>Post started on ".$f_Time.". </div>
</div>
<div id='Grp_Cell' style='float:right;width:600;'>
<div id='Tbl_Cel'>Subject: ".$f_Topic."</div>
<div id='Tbl_Cel' style='background-color:777777;height:150;'>". $f_Post."</div>
<a onClick='Reply(".$f_Index.");Filter();'><div id='Tbl_Cel' style='background-color:#888888; height:50; width:50; float:right; padding:2;border-color:black; border:2;'><br>Reply</div></a>
</div> ";

extract a portion of text from mysql mediumtext field to make turn.js book page with php

im using turn.js and custome php code to load joomla articles of a specific category to make a flipbook... its working fine till i have one article for one page. I add/edit article then save it and then view it on book page... this is a tedious task to do... now suppose i have all the content of a book in a joomla article and i want to dynamically load a portion of it as a page to make the book page and so on make pages till end of article... this seems doable if i only have text with fix no of lines. But the problem is the content can have images and headings as well... so how can i dynamically vary the portion of the article to be extracted for a single page based on contents to avoid overflow of book page...
here's the working code of the book where i have one article for one page...
<?php
//get total pages code from uncategorized (default) category. (id=2)
//state 1 means published -2 for trashed
$qry="SELECT count(*) FROM `sdad_content` WHERE `catid`= '2' and `state` ='1' ";
$get_db->setQuery($qry);
$total_pages=$get_db->loadResult();
if($total_pages){
$qry="SELECT `id` FROM `sdad_content` WHERE `catid`= '2' AND `state`='1' ORDER BY `id`";
//echo "<< $qry >>";
$get_db->setQuery($qry);$get_db->query();
$total=$get_db->getNumRows();
if ($total >= 1 ) { //execute this only if we have some results
$ids = $get_db->loadAssocList();
}
}
//echo $total_pages;
for($i=0; $i<$total_pages; $i++){
$qry="SELECT `introtext` FROM `sdad_content` WHERE `catid`= '2' AND `id`= '".$ids[$i]['id']."'";
$get_db->setQuery($qry);
$cover = $get_db->loadResult();
if($i%2==0){
$class='even';
$pnoclass="pnoright";
}else{
$class='odd';
$pnoclass="pnoleft";
}
echo '<div class="text '.$class.' "> <div class="page"> '.$cover;
echo '<div class="'.$pnoclass.' "> </div>';
echo '</div> </div>';
}
//code for back cover
//adjusting the last odd page if ends at odd insert a page to make it even
if($total_pages%2!=0){
echo '<div class="text odd "> <div class="page">';
echo '<div class="pnoleft"></div>';
echo '</div> </div>';
}
echo '<div class="text even "> <div class="page"> '.$covers[1]["introtext"];
echo '<div class="pnoright"></div>';
echo '</div> </div>';
echo '<div class="cover"> '.$covers[3]['introtext'].' </div>';
?>
I strongly recommend you to simplify code, so many mysql queries for nothing...
My offer (works the same way):
<?php
$qry="SELECT `introtext` FROM `sdad_content` WHERE `catid`= '2' AND `state`='1' ORDER BY `id`";
$get_db->setQuery($qry);
$results = $get_db->loadObjectList();
if (count($results)){
foreach($results as $key => $item){
if($key%2==0){
$class='even';
$pnoclass="pnoright";
} else {
$class='odd';
$pnoclass="pnoleft";
}
echo '<div class="text '.$class.' "> <div class="page"> '.$cover;
echo '<div class="'.$pnoclass.' "> </div>';
echo '</div> </div>';
}
}
?>
Less code, only 1 query (insted of N) and same result :)

load images dynamically in php from mysql database into a jquery slider

I have written a web application that involves having users upload pictures to the site. On the homepage, I dynamically show the newest pictures/items uploaded in PHP, limiting it to ten. However, the page looks so static and I have searched on Google, bing, ask, yahoo, etc for days now and haven't had any answers.
I have written the code to store store the images, and get them from the db.
The images are shown on the homepage, and the only thing i have left to do is load it in a slider.
$sql = mysql_query("SELECT * FROM items ORDER BY item_date_added DESC LIMIT 10")or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
//$user_id = $row['user_id'];
$item_name = $row['item_name'];
$item_id = $row['item_id'];
$check_pic = "users/$item_name.jpg";
if (file_exists($check_pic)) {
$show_pic = "<img src=\"users/$item_name.jpg\" width=\"100px\" height=\"100px\" border=\"5\" id='img'/>";
//$user_pic3 = "<img src=\"users/$rid/image01.jpg\" width=\"50px\" height=\"50px\" border=\"1\" />";
//$MemberDisplayList .= '' . $user_pic3 . '';
$i++;
$show_new_items .= "<a href='item_view?item_id=$item_id&&session_item=$item_id'>$show_pic</a>";
}
$newly_listed_names .= " <a href='item_view?item_id=$item_id&&session_item=$item_id'> $item_name </a> | ";
}
///////// END SHOW NEWLY ADDED ITEMS ///////////////////////////////////////////////////
the newly added items in echoed in a div in the body.
Can anyone help me please! it's been bothering me for a while now. Thanks.
To use Nivo, you need to generate html that looks something like this... (Download the nivo demo and open up the demo.html for the full source).
So all you need to do is output your images in a loop inside the slider div.
<div id="wrapper">
<div class="slider-wrapper theme-default">
<div id="slider" class="nivoSlider">
<?php
while($row = mysql_fetch_array($sql)){
$item_name = $row['item_name'];
$item_id = $row['item_id'];
$check_pic = "users/$item_name.jpg";
if (file_exists($check_pic)) {
print "<img src=\"users/$item_name.jpg\"/>";
$i++;
}
}
?>
<img src="images/2.jpg" data-thumb="images/2.jpg" alt=""/>
</div>
</div>
</div>
<script type="text/javascript" src="scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../jquery.nivo.slider.js"></script>
<script type="text/javascript">
$(window).load(function() {
$('#slider').nivoSlider();
});
</script>
You can use jquery plugins such as Nivo. Or you can try different jquery plugin from this link. And integrate it with your code.

Categories