WHILE loops can't be used twice? PHP - 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

Related

How to display 10 records per page and then how to use pagination?

One record
10 records loop
I have trouble with displaying properly records, end after that i need to use pagination.
v_news.php
<div class="news">
<a href="index.php?ogloszenie='<?php $row['id_article']; ?>'">
<div class="newstitle">
<?php echo $row['title'];?>
</div>
<div class="newsauthor">
<?php echo $row['username'];?>
</div>
<div class="newscomment">
comments: 56
</div>
<div class="newsdate">
<?php echo $row['timestamp'];?>
</div>
</a>
</div>
m_news.php
<?php
if(!isset($_SESSION['id'])){
header("Location: index.php");
exit();
}else{
$result = $Database->query("SELECT * FROM article LIMIT 0, 10");
if($result->num_rows != 0){
$rows = $result->fetch_assoc();
foreach ($rows as $row){
include("views/v_news.php");
}
}else{
echo "No results";
}
}
With foreach loop i have an error illegal string offset with $row['']. I don't know what to do with this.
First try to fix your 2nd line of code in v_news.php.
You forgot to use "echo".
<a href="index.php?ogloszenie='<?php $row['id_article']; ?>'">
change to:
<a href="index.php?ogloszenie='<?php echo $row['id_article']; ?>'">
fetch_assoc() fetches one row, not all.
You can use a while loop which will end once fetch_assoc() stops returning new rows.
while($row = $result->fetch_assoc()){
include("views/v_news.php");
}
For pagination, you only need to change LIMIT parameters
i.e. LIMIT 10,10 would be the second page data (10 total rows starting with row 10).
Also as bobiczeq pointed out you should ensure the echo statement appears in <?php $row['id_article']; ?> otherwise this is only empty.
I found correct answer.
$rows = mysqli_fetch_all($result, MYSQLI_BOTH);
Now it's working correctly.

Code is not displaying first result

About this code:
<?php
$result = mysqli_query($connect,"SELECT subcategories.subcat_name, subsubcategories.subsubcat_name FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subsubcategories.subcat_ID = 1");
$subcat_name = mysqli_fetch_array($result);
?>
<div class="grid_5 alpha omega" id="titlescontent"><p class="titlebar"><?php echo $subcat_name['subcat_name'];?></p></div>
<div class="clear"></div>
<div class="grid_5 alpha omega" id="content"><ul class="subcat">
<?php
while ($row=mysqli_fetch_array($result)){
?><li><?php echo $row['subsubcat_name'];?></li><?php
}
?>
</ul></div>
<div class="clear"></div>
For some reason it starts displaying the subsubcat_name from the 2nd result and not the first one which I also want to be displayed. Any idea how come and what I need to change in this code?
Actually, I see you need that first one for the title? In that case, try this alternate approach:
Replace your while loop with:
$row = $subcat_name;
do {
echo "<li>".$row['subsubcat_name']."</li>";
} while($row = mysqli_fetch_array($result));
What does this change? It basically means the loop body will run for your initial row, then for the rest.
you have extra mysqli_fetch_array call

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{ while{code}} not working wright

I have noticed that if i have a while{ while{}} loop, not all the data in a MYSQL database is shown...
here is the PHP (this is a working code...)
<?php
$conn = mysql_connect("localhost","xfiddlec_user","public");
mysql_select_db("xfiddlec_max");
mysql_set_charset("UTF8", $conn);
?>
<script>
$(function()
{
var icons =
{
header: "ui-icon-circle-arrow-e",
activeHeader: "ui-icon-circle-arrow-s"
};
$( "#dam" ).accordion({
icons: icons,
heightStyle: "content",
collapsible: true
});
});
</script>
<?php
$construct ="SELECT * FROM Noutati";
$constructaug ="SELECT * from Noutati WHERE MONTH(DataIntroducere) = 8 AND YEAR(DataIntroducere) = YEAR(CURDATE())";
$run = mysql_query($construct) or die(mysql_error());
$runaug = mysql_query($constructaug) or die(mysql_error());
$foundnum = mysql_num_rows($run);
$foundnumaug = mysql_num_rows($runaug);
if ($foundnum==0)
{
echo "Nu avem noutăți!";
}
else
{
echo"<div id='dam'>";
while($runrows = mysql_fetch_assoc($runaug) )
{
echo"
<h3>August 2013</h3>
<div><br>";
while($runrows = mysql_fetch_assoc($runaug))
{
$Luna = $runrows ['Luna'];
$Ziua = $runrows ['Ziua'];
$Mesaj = $runrows ['Mesaj'];
echo "
<table class='noutatitabel'>
<tr>
<td class='faramargini'>
<div class='data'>
<div class='luna'>$Luna</div>
<div class='ziua'>$Ziua</div>
</div>
</td>
<td class='albastru'>$Mesaj
</td>
</tr>
</table><br>";
}
echo"
<br><hr><br></div>";
}
echo"</div>";
}
?>
The database contains 6 rows.
When the above code is executed, an accordion menu appears but only 2 rows of that database are shown (for the specific month - the 1-st row is not shown) and i just don't understand where is the problem. If i remove the first while loop, the query shows 3 rows. I also have a fiddle for this and can be found here.
Have I done something wrong? Have you ever encountered this? How can i solve this problem?
Thank you.
And why exactly do you have these two loops? They're both going through the same mysql result resource, so they're interfering with each other.
I think you want to do something like this:
if(mysql_num_rows($runaug) > 0 )
{
echo"
<h3>August 2013</h3>
<div><br>";
while($runrows = mysql_fetch_assoc($runaug))
{
you can't use the pointer from mysql_fetch_assoc($runaug) to run nested loops. because once the child loop finish iterating the parent loop will have gone past the end of the result as well. If you really just want to run two loops use
mysql_data_seek($rs,$offset);
you will have to keep a reference to the offset of the parent loop when you enter the child loop and then reset the pointer accordingly.
Change your code to use just one while:
else
{
echo"<div id='dam'>";
if($foundnumaug)
echo"<h3>August 2013</h3><div><br>";
while($runrows = mysql_fetch_assoc($runaug) )
{
$Luna = $runrows ['Luna'];
$Ziua = $runrows ['Ziua'];
$Mesaj = $runrows ['Mesaj'];
echo "
<table class='noutatitabel'>
<tr>
<td class='faramargini'>
<div class='data'>
<div class='luna'>$Luna</div>
<div class='ziua'>$Ziua</div>
</div>
</td>
<td class='albastru'>$Mesaj
</td>
</tr>
</table><br>";
}
echo"<br><hr><br></div>";
}
echo"</div>";
}
The reason of your problem is that the first while fetches first row and moves the internal data pointer to the next row, than the second while fetches all remaining rows.
First of all, you should use the improved mysql extension, mysqli
After that, I'm sure that you don't want to exact same loops, so revise them, most likely you are losing data there.
So if I understand correctly from the comments, the first WHILE is used to check if there are any results.
Then you need to change the first WHILE:
while($runrows = mysql_fetch_assoc($runaug) )
INTO
if ( mysql_num_rows($runaug) > 0 )
Otherwise the first WHILE will consume your first row. So you will never show the first row.

error outputting html with javascript

I have this php code, with which I am trying to generate a popup window that will contain the contents of a html file, however after adding in the script tags, no html is displayed. I tried echoing out $row2, but the word array is printed to the screen and nothing else.
<?php
session_start();
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
die("You should have a 'cmd' parameter in your URL");
$pk = $_GET["pk"];
$con = mysql_connect("localhost","root","geheim");
if(!$con)
{
die('Connection failed because of' .mysql_error());
}
mysql_select_db("ebay",$con);
if($cmd=="GetAuctionData")
{
$sql="SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'";
$sql2="SELECT ARTICLE_DESC FROM Auctions WHERE ARTICLE_NO ='$pk'";
$htmlset = mysql_query($sql2);
$row2 = mysql_fetch_array($htmlset);
echo $row2;
echo '<script>
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write('.$row2["ARTICLE_DESC"].');
child1.document.close();
}
</script>';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
echo "<div id='leftlayer'>
<strong>Article Number</strong> ".$row['ARTICLE_NO']."
<p><strong>Article Name</strong></p> ".$row['ARTICLE_NAME']."
<p><strong>Subtitle</strong></p> ".$row['SUBTITLE']."
<p><strong>Username</strong></p> ".$row['USERNAME']."
<p><strong>Total Selling</strong></p> ".$row['QUANT_TOTAL']."
<p><strong>Total Sold</strong></p> ".$row['QUANT_SOLD']."
<p><strong>Category</strong></p> ".$row['CATEGORY']."
<p><strong>Highest Bidder</strong></p> ".$row['BEST_BIDDER_ID']."
</div>
<div class='leftlayer2'>
<strong>Current Bid</strong> ".$row['CURRENT_BID']."
<p><strong>Start Price</strong></p> ".$row['START_PRICE']."
<p><strong>Buyitnow Price</strong></p> ".$row['BUYITNOW_PRICE']."
<p><strong>Bid Count</strong></p> ".$row['BID_COUNT']."
<p><strong>Start Date</strong></p> ".$row['ACCESSSTARTS']."
<p><strong>End Date</strong></p> ".$row['ACCESSENDS']."
<p><strong>Original End</strong></p> ".$row['ACCESSORIGIN_END']."
<p><strong>Auction Type</strong></p> ".$row['AUCTION_TYPE']."
</div>
<div class='leftlayer2'>
<strong>Private Auction</strong></p> ".$row['PRIVATE_AUCTION']."
<p><strong>Paypal Accepted</strong></p> ".$row['PAYPAL_ACCEPT']."
<p><strong>Auction Watched</strong></p> ".$row['WATCH']."
<p><strong>Finished</strong></p> ".$row['FINISHED']."
<p><strong>Country</strong></p> ".$row['COUNTRYCODE']."
<p><strong>Location</strong></p> ".$row['LOCATION']."
<p><strong>Conditions</strong></p> ".$row['CONDITIONS']."
</div>
<div class='leftlayer2'>
<strong>Auction Revised</strong></p> ".$row['REVISED']."
<p><strong>Cancelled</strong></p> ".$row['PRE_TERMINATED']."
<p><strong>Shipping to</strong></p> ".$row['SHIPPING_TO']."
<p><strong>Fee Insertion</strong></p> ".$row['FEE_INSERTION']."
<p><strong>Fee Final</strong></p> ".$row['FEE_FINAL']."
<p><strong>Fee Listing</strong></p> ".$row['FEE_LISTING']."
<p><a href='#' onclick='makewindows(); return false;'>Click for full description </a></p>
</div>";
$lastImg = $row['PIC_URL'];
echo "<div id='rightlayer'>Picture Picture
<img src=".$lastImg.">
</div>";
}
}
mysql_close($con);
?>
edit: I have fixed the errors that Roborg pointed out, however the script will still not load and does not give a precise error.
i have updated the code above
As well as the missing </script>,
child1.document.write('.$row2["ARTICLE_DESC"].')
should be
child1.document.write(' . json_encode($row2["ARTICLE_DESC"]) . ');
The json_encode() function will take care of any quoting for you.
Edit:
<a href='#' onclick=makewindows()> should be <a href='#' onclick='makewindows(); return false;'> - You should have quotes there, and the return false will stop you getting taken to "#" when you click the link.
Also, from memory I'm not sure you can open about:blank and then write to it - I think it sees that as cross-domain scripting. You might be better off creating a minimal "blank.html" file on your server and using that.
You have to print_r an array, like print_r($row2);
In this line:
$row2 = mysql_fetch_array($htmlset);
You are setting $row2 to be an array representing an entire row of the result from your query. Even if the "row" is just one field, it's still an array. If you want to get just the value of the first field, you can use mysql_result.
The parameters are: resource $result , int $row [, mixed $field ] so an example of the usage would be:
// get the first field of the first row
$fieldVal = mysql_result($htmlset, 0);
// get the third field
$fieldVal = mysql_result($htmlset, 0, 2);
// get the first field of the 2nd row
$fieldVal = mysql_result($htmlset, 1);
Your <script> tag is never closed and your JavaScript instructions are not ended with semicolons. It might be the source of the problem.

Categories