why am I getting unexpectedly repeated results from my php file? - php

Yes, I've looked around and yes I've used mysql_fetch_array hundreds of times successfully before. I want a php file that will output an html file with some constants and a few interpreted php variables. After an hour, this is where I'm at.
<?php
require "(this is sql statement to get all rows from the db).php";
$i = 1;
while($row = mysqli_fetch_array($results_getpieces) && $i < 11 ){ ?>
<li>
<a href="#image-1">
<img src="<?php echo $row['content']; ?>" alt="image01">
<span><?php echo $row['title']; ?></span>
</a>
<div class="lb-overlay" id="image-1">
<img src="<?php echo $row['thumb']; ?>" alt="image01" />
<div>
<h3>blahblah <span>bluelue</h3>
<p>sherpas don't dance</p>
Prev
Next
</div>
x Close
</div>
</li>
<?php
$i++;
}
?>
When I display the $row results in a table, there's no problem. Before I added that i++ business, I could get the first record from my results, but it would just repeat those results for all ten instances.
Help almighty stackers, and overflow me with your knowledge. Please. I can't go to sleep until I get this. Where am I going wrong?

You need to parenthesize the condition appropriately, so that the array that you get back from the function call doesn't get "and"-ed with the condition "$i < 11":
($row = mysqli_fetch_array($results_getpieces)) && $i < 11

Related

how to put div in a for loop

For parsing a list of articles, i have this code to parse all the articles:
while($article = $articles->fetch())
{
$date = strtotime($article['createdAt']);
$formatted_date = date("F Y",$date);
?>
<br />
<div class="news-content">
<div class="news-image">
<?php echo $article['title']; ?>
</div>
<div class="news-article">
<h3>
<span><?php $date = strtotime($article['createdAt']); echo /*date("F j",$date);*/ strftime('%e %B',$date) ?></span>
<br />
<?php echo $article['title']; ?>
</h3>
</div>
</div>
<?php
} //end while loop
?>
What i want to achieve: only the first 5 <div class="news-content">...</div> should be shown.
I know i have to do something with a for loop
but i do not know exactly how to use the for loop for this situation...
Can someone help me with that?
There are a lot of different ways to limit a loop. One possibility is to use a for loop instead of a while loop. for is often a good option if you want something to happen a specific number of times. Adding something else like fetch into the continuation condition will mean it happens up to a specific number of times.
for ($i = 0; $i < 5 && $article = $articles->fetch(); $i++) {
// output article
}

Repeating an HTML element with incrementing variables

I currently have a simple html list. What I want is to repeat this list item with each repeated element having a variable that will increase by one, each time it is repeated.
The php calls that i have included in the above list item is from the Advanced Custom Field plugin on WordPress. The variable I want to change is the number inside of those php calls.
<ul>
<li>
<?php the_field('vendor_1_name'); ?> <!--the number is the variable that i want to increase by one with each repition-->
<a href="http://<?php the_field('vendor_1_url'); ?>" target="_blank"/>
<?php the_field('vendor_1_url'); ?>
</a>
</li>
</ul>
I have an idea of how to do this using an array, but I would love to hear other methods on how to do something like this. Thanks!
<ul>
<?php for ($z = 0; $z < $n; $z++) : ?>
<li>
<?php the_field('vendor_'.$z.'_name'); ?>
<a href="http://<?php the_field('vendor_'.$z.'_url'); ?>" target="_blank">
<?php the_field('vendor_'.$z.'_url'); ?>
</a>
</li>
<?php endfor; ?>
</ul>
Where $n is the number of times it should iterate.
Use a for loop. If you have an array of items (are you grabbing vendors from a database?), just iterate through the array:
<?php
// fetch values and define $vendors
// using sql is highly recommended
echo "<ul>\n";
for ($i = 0; $i < count($vendors); $i++) {
echo "<li><a href='".$vendors[$i]['vendor_url']."'>".$vendors[$i]['vendor_name']."</a></li>\n";
}
echo "</ul>\n";
?>
Note that the array would say vendor_name instead of vendor_1_name because the field is not going to have the iteration in its name.

Writing php code based on SQL count

If you look at the jsfiddle you'll notice modules in yellow and red. I have all my code working except that I have to manually input the html/php for the modules.
http://jsfiddle.net/W6zYA/1/
My module code is:
<?php $row = mysql_fetch_row($result); ?>
<a href='#' data-reveal-id="<?php echo $row[0]; ?>" data-animation="none" >
<div class="grid_3">
<p id="contexttitle">
<?php echo $row[1]; ?>
<span style="float:right;"> <?php echo $row[3]; ?> </span>
</p>
<p id="accesssubmenu">Last Update: <?php echo $row[6]; ?> </p>
</div>
</a>
<div id="<?php echo $row[0]; ?>" class='reveal-modal'>
<h1> <?php echo $row[1]; ?> </h1>
<p> <?php echo $row[4]; ?> </p>
<p4>Last Update: <?php echo $row[6]; ?> </p4>
<a class="close-reveal-modal">×</a>
</div>
What I'm wanting to do is have it create X amount of these modules based on a SQL Query where I count the # of rows in each section (red, yellow, green).
I tried to store the php in the SQL database and after research found out that this is bad practice and shouldn't be done even when using eval() as there will be user input. I also read about PHP templates such as Smarty but wasn't certain if that was the correct solution for me.
If someone can point me in the right direction I'd greatly appreciate it I'm just not sure where to start/what to google.
mysql_fetch_row only fetches one row. If you have multiple rows you need mysql_fetch_assoc or mysql_fetch_array and use something like a foreach loop to loop through the results. This will output the html as many times as results in the MySQL query.
Try mysql_num_rows($result) that will give you the number of rows returned by the query. I would try to upgrade to PDO or mysql since the mysql_* functions are going to be deprecated in PHP 5.5
http://php.net/manual/en/function.mysql-num-rows.php
I assume, that you get multiple records from you database? That way you can use a while loop to loop trough your result.
while ($row = mysql_fetch_row($result)) {
// do you html code here.
}
That should do the trick.

Loop through PHP function, display userdata from Mysql - limit to display to 25 items and add next button

I have this PHP function, which I use to display my userdata. If run once it will basicly display a div with the userdata in it.
function listings($fornavn, $efternavn, $email, $adresse, $tlf, $postnr, $city, $fodselsdag, $brugerid,$bartype,$idbar)
{
?>
<div class="container">
<span class="records" id="id-<?php echo $brugerid;?>">
<div class="customer bidDiv clearfix">
<?php if ($bartype=='temp_vip') { ?>
<ul>
<li>
<span class="actionSpan" id="<?php echo $brugerid;?>" value="<?php echo $idbar;?>">
<a class="edit-opt" id="godkend" href="#">GODKEND</a>
</span>
</li>
<li>
<span class="actionSpan" id="delete-<?php echo $brugerid;?>" value="<?php echo $bartype;?>">
<a class="delete-opt" id="delete" href="#">Afvis</a>
</span>
</li>
<?php }else{ ?>
<ul>
<li>
<span class="actionSpan" id="delete-<?php echo $brugerid;?>" value="<?php echo $bartype;?>">
<a class="delete-opt" id="delete" href="#">Slet</a>
</span>
</li>
<li>
<a class="edit-opt" href="editform.php?id=<?php echo $brugerid."&bartype=".$bartype;?>" rel="facebox">Rediger</a>
</li>
<?php if ($bartype =='vip'){?>
<li>
<a class="print-opt" href="print.php?id=<?php echo $brugerid;?>" rel="facebox">Print</a>
</li>
<?php }else{
// Dont render vip link
}}?>
</ul>
<p class="contact-data">
<?php echo $email;?><br>
Tlf.: <?php echo $tlf;?>
</p>
<div class="base-data">
<h4><?php echo ucwords($fornavn)." ".ucwords($efternavn);?></h4>
<p>Fødselsdag <?php echo $fodselsdag;?></p>
<address><?php echo ucwords($adresse) ." ". $postnr ." ". ucwords($city);?></address>
</div>
</div><!-- end customer -->
</div>
</span>
<?php
I mostly use this function in a loop, to display all users from my MySQL database, who has a specific relation to something else.
This is all working great. But currently it would pull all results at once. Right now I only have 5 members, so its no problem, but say I get 800 or 2000 members, the list of users would get very long.
So I want to implement some kind of limit on how many users it displays, but still be able to browse through all the users. Many sites use something like pages and split up the results that way. Links like:
[1] [2] [3] [Last page>>]
I can't figure out how to start doing this? How would I proceed?
Also looked into this Jquery plugin:
http://andersonferminiano.com/jqueryscrollpagination/
But it keeps reloading my PHP file which results in the Loops being restarted, and it simply displays the results over and over again endlessly.
Can someone help me with the logic behind creating this? Or better, point me in a direction where I could use the jquery pluging above - where it only loads the loop one time, and renders the results as I scroll.
Any help or pointers will be greatly appreciated!
Thanks
Jquery pagination by default will only break-up the given table into several tabs on the page, that is all the data is actually loaded. There are some that let you do an AJAX request to fetch the next page, to work in conjunction with your PHP code.
Ideally, you want to limit the query using LIMIT (number of rows in the result object) and OFFSET (Start from row X ) which will give you number of records starting from your offset row up until the limit, and then use logic on the PHP side to determine the maximum number of pages.
$page = $_POST["page"] * 25; // make sure that page 0 is the starting page or calculate
$SQL = "SomeQueryText LIMIT 25 OFFSET '$page'" ;
$result = query ($SQL);

Two identical while loop functions, the second doesn't work

I've got a problem with my php script. The script generates two <ul>'s, one with the images, another with the thumbnails. The php runs through the first while loop perfectly, but my <ul> for thumbnails always comes back empty. I've been working through it to no luck, and I can't seem to get the script to print any errors. Help?
include "../backend/connect.php";
$query = "select image_id from images where thumb != '';";
$result = mysql_query($query);
<div id="main">
<div id="container">
<ul>
<?php
while ($row = mysql_fetch_array($result)) {
$img_id = $row['image_id'];
?>
<li class="hidden" id="<?php print($img_id); ?>" style="background-image:url(/pull.php?id=<?php print($img_id);?>&thumb=false)"></li>
<?php } ?>
<li class="" id="focus"></li>
</ul>
</div>
</div>
<div id="side">
<div id="photos"><ul>
<?php
while ($row = mysql_fetch_array($result)) {
$img_id = $row['image_id'];
?>
<div class="imgDiv" id="<?php print($img_id); ?>" >
<li>
<img src="pull.php?id=<?php print($img_id);?>&thumb=true" class="thumbnail"/>
</li>
</div>
<?php
}
?>
</ul></div>
</div>
</div>
you're using a while loop to loop through the results, you cant do it twice.
Call mysql_data_seek($result, 0); to reset the internal pointer back to the first record after your first time through the results to start over.
It sounds like maybe you read all the rows in the first loop, and there's nothing left to read by the time you get to the second loop :)
Your first while loops until mysql_fetch_array($result) is false/empty. You never assign a new value to $result, so when you get to your second while it skips the loop.
If you want to iterate through the results twice, dump them into an array and use foreach to iterate through it.
The first time you loop through the results, you are actually clearing the $result object. You could possibly loop through once doing something like:
$image_ids = array();
while ($row = mysql_fetch_array($result)) {
array_push($img_ids, $row['image_id']);
}
?>
and then loop through that array while generating your code.

Categories