PHP MYSQL while loop with if statement echoing in wrong order - php

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>
";

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)

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?

How can I update with a form using MYSQLI

I'm lost on MySQLi. Manages a blog on standard mysql query, MySqli threw me. Followed a tutorial for inserting into a database. Notice the link for Edit. Not sure how to jump to a edit page to update. It this the wrong way of doing it? I think it's the echo that is the echo that is the issue?
<?php
$sql = "
SELECT snippets.Title, snippets.Link, snippets.Text, snippets.Created, camp_names.ribbon as Ribbon, camp_names.alt_text, camp_names.name as Campaign, camp_names.id
FROM snippets
LEFT JOIN camp_names ON snippets.Campaign = camp_names.id
ORDER BY camp_names.id ASC
";
$results = $db->query($sql);
if($results->num_rows) {
While($row = $results->fetch_object()) {
echo "
<div class='snippets'>
<div class='title'><h5><a href=''>{$row->Campaign}</a></h5><strong>{$row->Title}</strong> - Created:{$row->Created}</div>
<div class='ribbon_wrapper'>
<div class='ribbon'><img src='{$row->Ribbon}' alt='{$row->alt_text}' /></div>
<div class='ribbon_text'>{$row->Text}...<a href='{$row->Link}'> Read more</a></div>
<a href='#'>edit</a>
</div>
</div>
";
}
} else {
echo 'No Results';
}
?>

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
}

Making a content "feed" with mysql database and php, is this a safe way?

I'm making a a side bar feed that will display the 10 most current things submitted into my database. I'm very new to all of this, so I am wondering.. is this an ok way of going about doing it? it works.. not automatically but when i submit something into my database, it goes there.. i submit something else and then the top goes to to the second..! i just cant shake the feeling that maybe this isnt a good way to do it.
the top 3 sections
<div class="span3 offset3">
<?php include 'feed/one.php'; ?>
<ul class="nav nav-list well">
<li class="nav-header"></li>
<li class="active">HIT INFO</li>
<?php while($row = $data->fetch_assoc()) { ?>
<li><a href="<?php print $row['link']?>"><?php
Print "<tr>";
Print "<th>Hit:</th> <td>".$row['hit'] . "</td> ";
Print "<th>Amount:</th> <td>".$row['amount'] . " </td>";
Print "<th>Category:</th> <td>".$row['category'] . "</td></tr> ";
Print "<br><br/>";
Print "</table>";?></a></li>
<?php } ?>
<li class="divider"></li>
<?php $data = $mysqli->query("SELECT * FROM hit ORDER BY hit_id DESC LIMIT 1, 1"); ?>
<?php while($row = $data->fetch_assoc()) { ?>
<li><a href="<?php print $row['link']?>"><?php
Print "<tr>";
Print "<th>Hit:</th> <td>".$row['hit'] . "</td> ";
Print "<th>Amount:</th> <td>".$row['amount'] . " </td>";
Print "<th>Category:</th> <td>".$row['category'] . "</td></tr> ";
Print "<br><br/>";
Print "</table>";?></a></li>
<?php } ?>
<li class="divider"></li>
<?php $data = $mysqli->query("SELECT * FROM hit ORDER BY hit_id DESC LIMIT 2, 1"); ?>
<?php while($row = $data->fetch_assoc()) { ?>
<li><a href="<?php print $row['link']?>"><?php
Print "<tr>";
Print "<th>Hit:</th> <td>".$row['hit'] . "</td> ";
Print "<th>Amount:</th> <td>".$row['amount'] . " </td>";
Print "<th>Category:</th> <td>".$row['category'] . "</td></tr> ";
Print "<br><br/>";
Print "</table>";?></a></li>
<?php } ?>
<li class="divider"></li>
<?php $data = $mysqli->query("SELECT * FROM hit ORDER BY hit_id DESC LIMIT 3, 1"); ?>
<?php while($row = $data->fetch_assoc()) { ?>
<li><a href="<?php print $row['link']?>"><?php
Print "<tr>";
Print "<th>Hit:</th> <td>".$row['hit'] . "</td> ";
Print "<th>Amount:</th> <td>".$row['amount'] . " </td>";
Print "<th>Category:</th> <td>".$row['category'] . "</td></tr> ";
Print "<br><br/>";
Print "</table>"; ?></a></li>
<?php } ?>
the data that gets submitted gets displayed on my main page until something else gets submitted, goes to the "feed", and also goes to another page that shows the past data.
You don't appear to have anything the user can intercept, so "safe" is a non issue.
You are querying illogically though. There's no reason to repeat the same query with multiple offsets all over the page when you can just fetch the data initially and use that object to relay the content where needed. Run a query like this at the beginning of the file, or ideally before any output is rendered.
"SELECT * FROM hit ORDER BY hit_id DESC LIMIT 4"
Now you have 4 items, so accessing those throughout the page could be something like this:
<ul class="nav nav-list well">
<li class="nav-header"></li>
<li class="active">HIT INFO</li>
<?php while($row = $data->fetch_assoc()): ?>
<li>
<a href="<?php print $row['link']?>">
<table>
<tr>
<th>Hit:</th> <td><?php echo $row['hit']; ?></td>
<th>Amount:</th> <td><?php echo $row['amount']; ?></td>
<th>Category:</th> <td><?php echo $row['category']; ?></td>
</tr>
<br><br/>
</table>
</a>
</li>
<li class="divider"></li>
<?php endwhile; ?>
</ul>
Now, you have a few markup errors there. You close a table you never open. This can only in a small way be considered tabular data, so tables are probably not the best way to do this anyhow. I myself don't understand your use of th and td in this way, but if it works for you then good.
You should break out of php to display html. echoing something like "<th>" is totally unnecessary.
Instead of each time querying the database and getting a record to show it, you should do it in a single query which fetches the number of rows you need:
<?php $data = $mysqli->query("SELECT * FROM hit ORDER BY hit_id DESC LIMIT 1, N"); ?>
This fetches the first N rows, where N has to be numeric of course. Then you should loop throw the rows and print it just the way you are doing now. The only difference is that it might take you a while to get the nuances of opening/looping/closing tables correctly, but it is a really good investment of your time to wrap your head around it!
You're actually using the hit_id field to order the data you get from the database.
If you want actually to retrieve the "10 most current things submitted into my database", you'll need something else than an auto-incremented ID. (Something like a COUNT on the amount row). It will depends on the actual value / way to fill this field but it might look like this instead :
SELECT * FROM hit GROUP BY Category ORDER BY amount DESC;
Concerning this part :
but when i submit something into my database, it goes there.. i
submit something else and then the top goes to to the second
The reason is quite simple, you're using ORDER BY hit_id DESC, that's why the last inserted ID is coming first.

Categories