how can we handle while loop iteration? - php

I am having block of code which is working fine but the problem is that...
in one loop it print 'one' qoute.
in 2nd both 'one' and 'two'
in third all three
...so on till the loop execute.
I want to print only one in first time and second qoute in second time and so on till loop executes.
here is my block of code
<div class="records round">
<?php
//show records
$query = mysqli_query($con,"SELECT table2.col2 AS a,table1.col2 AS b, table1.col1 AS c, table1.q_url AS d
FROM {$statement}
LIMIT {$startpoint} , {$limit}");
$output='';
$Authorname='';
$count=1;
while ($row = mysqli_fetch_array($query)) {
$Authorname =$row['a'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url=explode('/',$url);
?>
<div class="record round"><?php echo $count; $output .='<a href="http://localhost/quotes/'.$url[5].'/'.$row['d'].'.html">';
echo $output .=$row['b'].'</a>';?></div>
<?php
$count++;
}
?>
</div>

What you are doing here appending string to $output variable so at each iteration its keeping appending.
Your $output variable must be empty before performing new iteration.
Thats the reason you are getting such output.
So to avoid this you have to reinitialize $output variable inside the loop.
Check below code:
while ($row = mysqli_fetch_array($query)) {
$output='';
$Authorname =$row['a'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url=explode('/',$url);
?>
<div class="record round"><?php echo $count; $output .='<a href="http://localhost/quotes/'.$url[5].'/'.$row['d'].'.html">';
echo $output .=$row['b'].'</a>';?></div>
<?php
$count++;
}

Related

Get two results while looping trough associative array in PHP

I want to get two results at a time when using while looping trough a associative array in PHP.
I need to echo two results per row, something like this:
<?
while($row = mysqli_fetch_assoc($result)) {
$client_name = $row['client_name'];
$review = $row['review'];
echo('
<div class="row">
<div>
<p>'.$client_name.'</p>
<p >'.$review.'</p>
</div>
<div>
<p>'.$client_name.'</p>
<p >'.$review.'</p>
</div>
</div>
');
}
}
?>
Right now it's giving me the same result twice rather than the next one.
You can use a counter to control the output of the outside div so that you get two inside div output for each outside one:
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$client_name = $row['client_name'];
$review = $row['review'];
if ($i % 2 == 0) echo '<div class="row">';
echo '<div><p>'.$client_name.'</p><p>'.$review.'</p></div>';
if ($i % 2 == 1) echo '</div>';
$i++;
}

How to echo result in list using php

I want to print sql result in list using php.
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
while ($row = $q->fetch_assoc()) {
$hh=$row['name'];
}
?>
<ul id="myUL">
<li><?php echo $hh ?></li>
</ul>
like:-
.Mango
.Apple
.Banana
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
echo "<ul id="myUL">";
while ($row = $q->fetch_assoc()) {
echo "<li> <a href='#'>".$row['name']."</a></li>";
}
echo "</ul>";
?>
Generate the HTML in the for loop
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
$hh = ''; //empty string first
while ($row = $q->fetch_assoc())
{
$hh .= '<li>' . $row['name'] . '</li>';
// ^--------------------- concat with the previous result
}
?>
<ul id="myUL">
<?php echo $hh; /* display */ ?>
</ul>
$hh will be the last fetched value because it's being rewritten on every loop cycle. You need to append to that instead. Take a look at this:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$query = "SELECT name FROM tablename";
$query = mysqli_query($con, $query)or die("Failed to fetch data");
$lis = "";
// as long as row is not empty
while ($row = $q->fetch_assoc()) {
$lis .= "<li> <a href='#'>".$row['name']."</a></li>";
}
echo "<ul>$lis</ul>";
?>
The issue is that $hh is always the last row since while($row = $q->fetch_assoc()) over writes the value of the variable with each row.
In order to output a column value in each row, you need to place the output inside of the while loop: it will do it once for each record.
You can use conditional statements for readability:
<!-- Start of List -->
<ul id="myUL">
<?php
$query = "select name from plant ";
$q = mysqli_query($con,$query) or die("Could Not Perform the Query");
while ($row = $q->fetch_assoc()):
?>
<!-- Option -->
<li><?= $row['name']; ?></li>
<?php endwhile; ?>
</ul>
<!-- End of List -->
Like referenced by #Cid in the comments, each element needs to be added inside of the list. Keep your <ul> outside of the loop.
In pseudo code, so you can understand better, it would look like this:
list
foreach row do:
output option
end foreach
end list

Why counter resets when I click on other link?

I have define a counter in while loop and it is initialized outside the loop.
I have echo the counter in loop itself. When I have 50 record on first page it displays 1 to 25. The problem is that on second page it start again from 1, not like it should work: to start it from 26 to 50.
Here is my code:
<?php
//show records
$query = mysqli_query($con,"SELECT table2.col2 AS a,table1.col2 AS b, table1.col1 AS c, table1.q_url AS d FROM {$statement} LIMIT {$startpoint} , {$limit}");
$Authorname='';
$count=1;
while ($row = mysqli_fetch_array($query)) {
$output='';
$Authorname =$row['a'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url=explode('/',$url);
?>
<div class="record round"><?php echo $count;$output .='<a href="http://localhost/quotes/'.$url[5].'/'.$row['d'].'.html">';
echo $output .=$row['b'].'</a>';?></div>
<?php
$count++;
}
?>
Edit
Try
$nbpage = 2;
$nbresultperpage=25;
$count = ($nbpage-1)*$nbresultperpage;
Where $nbpage is you're current number of page

Limit characters of data to display on webpage with substr

I want to display data from my database but I have the following problem. I would like to display only the first 120 characters of the row 'text'. I know I can do this with the substr function.
I tried to implement substrin my code, but no text is shown when I reload the webpage ...
The whole code:
(connect to database)
$sql = "SELECT * FROM `table-example`";
// perform the query and store the result
$result = $conn->query($sql);
$text= $row['text'];
// if the $result contains at least one row
if ($result->num_rows > 0) {
// output data of each row from $result
while($row = mysqli_fetch_array($result))
{?>
<div id="preview">
<div class="title">
<?php echo $row['title'];?>
</div>
<div class="subtitle">
<?php echo substr($text, 0, 120);?>
</div>
</div>
<?php
}// end while
}// end if
else {
echo '0 results';
}
?>
(close connection)
Can someone please explain to me how to solve this?
The solution is to place $text = $row['text'] within the while loop.
Since before that, you don't declare $row to anything, therefore $text doesn't get set. Because $text isn't set, the substr method will shorten nothing AKA the echo returns nothing.

WHILE loops can't be used twice? PHP

I am new to PHP , I hope someone can help me. I have a table which contains "id" , "img" , "link" and "desc" in mysql database . I want it to echo all out into something like this :
<div id="featured">
<a target='_blank' href='link'><img src='image link1' title='description'/></a>
<a target='_blank' href='link'><img src='image link2' title='description'/></a>
<a target='_blank' href='link'><img src='image link3' title='description'/></a>
<a target='_blank' href='link'><img src='image link4' title='description'/></a>
</div>
<div id="cap">
<span class='desc' id='idnumber'>Description1</span>
<span class='desc' id='idnumber'>Description2</span>
<span class='desc' id='idnumber'>Description3</span>
<span class='desc' id='idnumber'>Description4</span>
</div>
PHP CODE:
<?php
require_once "./dbconfig.php";
opendb();
$sql = "SELECT * FROM images ORDER BY id DESC";
$query = querydb($sql);
?>
<div id="featured">
<?php
while($row = mysql_fetch_array( $query )){
echo "<a target='_blank' href='$row[link]'><img src='$row[img]' title='$row[desc]'/></a>";
}
?>
</div>
<div id="cap">
<?php
while($row = mysql_fetch_array( $query )){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
closedb();
?>
</div>
Can WHILE being used twice or i am wrong? when i run this code , the second while loop is not working , the spans are not showing at all.
Please help.
The first loop consumes all data from mysql already, so there is nothing left in the second loop. You can store the rows data in the meanwhile however and then re-use that store.
<div id="featured">
<?php
$rows = array();
while($row = mysql_fetch_array( $query )){
$rows[] = $row;
echo "<a target='_blank' href='$row[link]'><img src='$row[img]' title='$row[desc]'/></a>";
}
?>
</div>
<div id="cap">
<?php
foreach($rows as $row){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
closedb();
?>
</div>
Use this before your second while loop
mysql_data_seek($query,0);
The DB reference ($query) acts as a pointer to the next unread record; when you call mysql_fetch_array(), it gets the record that is being pointed to, and moves the pointer to the next position.
Therefore, after looping through them all, the pointer will be pointing at the end of the record set, hence it returns false when you ask for the next record. Finishing the loop does not do anything else to the pointer; it remains pointing to the end of the record set.
So what you need to do is reset the pointer to the start of the data set before you can loop through it a second time.
The function to do this is mysql_data_seek();
Therefore you'd need the following line of code immediatly before your second loop:
mysql_data_seek($query, 0);
Hope that helps.
Fromt the docs for mysql_fetch_array
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
The internal data point is still at the end when you try to use your second while loop. You have done nothing to reset it.
You can move it back to the start with mysql_data_seek
You can use while twice, but see what it does:
It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE.
Once mysql_fetch_array has no more rows to fetch, it will return false on every subsequent call - so your first while loop will stop looping, as the expression mysql_fetch_array( $query ) is false; and since it's the same expression in the second while, that loop will never execute (as the expression evaluates to false).
What to do: If you want to loop over the results multiple times, I'd suggest to store the result rows into an array first, then loop over them. Simplified example:
$results = Array();
while ($row = mysql_fetch_rows($query)) {
$results[] = $row;
}
foreach ($results as $row) {
echo $row['something'];
}
mysql_fetch_array will be empty because you have already fetched all of the rows from the database. You will need to reset the pointer using mysql_data_seek.
<?php
mysql_data_seek( $query, 0 );
while($row = mysql_fetch_array( $query )){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
... rest of code
With mysql_fetch_array() you are going through the results step by step, till you are at the end. Or as the PHP docs say:
Returns an array that corresponds to
the fetched row and moves the internal
data pointer ahead.
This means, you need to start from new. So, use this before your second while:
mysql_data_seek($query,0);
try this
<?php
require_once "./dbconfig.php";
opendb();
$sql = "SELECT * FROM images ORDER BY id DESC";
$query = querydb($sql);
$query2 = querydb($sql);
?>
<div id="featured">
<?php
while($row = mysql_fetch_array( $query )){
echo "<a target='_blank' href='$row[link]'><img src='$row[img]'
title='$row[desc]'/> </a>";
}
?>
</div>
<div id="cap">
<?php
while($row2 = mysql_fetch_array( $query2 )){
echo "<span class='desc' id='$row2[id]'>$row2[desc]</span>";
}
closedb();
?>
$str_res1 ='';
$str_res2 ='';
while($row = mysql_fetch_array( $query )){
$str_res1 .= " a target='_blank' href='$row[link]' img src='$row[img]' title='$row[desc]' a";
$str_res2 .= "span class='desc' id='$row[id]'> $row[desc] span>";
}
sorry i couldn't complete html tags in my answer as it disappears from post if i write "<" or "/>"
by this you can take all values in php strings and you can echo it any where you want to .
$stuff = mysql_query("SELECT * FROM tbl");
while($s = mysql_fetch_array($stuff)){
//ur code
}
// add this line
mysql_data_seek( $stuff, 0 );
while($r = mysql_fetch_array($stuff)){
//ur code
}
mysql_data_seek($query, 0); is deprecated since php 5.5 and removed from php 7.0
use mysqli_data_seek($query, 0); instead

Categories