I am trying to query a database, but it seems to just load for an age and not do anything. It's a simple query and shouldnt take longer than a millisecond.
while($row = mysql_fetch_array(getWallPosts($userid)))
{
}
Now when I replace this code with:
echo mysql_num_rows(getWallPosts($userid));
It just displays '1' in fact there's only one record in the DB and it's just a simple SELECT statement.
Here's the getWallPosts function:
function getWallPosts($userid, $limit = "10")
{
$result = dbquery("SELECT * FROM commentpost
WHERE userID = ".$userid."
ORDER BY commentPostID DESC LIMIT 0, ".$limit);
return $result;
}
Also, when I put the SQL string that it's executing into MySQL's query browser. It takes no time at all.
Any ideas?
You appear to be looping indefinitely because you're retrieving a new set (one record) of data each time.
$result = getWallPosts($userid);
while ($row = mysql_fetch_array($result)) {
//printf($row[0]);
}
You need to get the data once and loop through it. Your code is getting the data, running the loop and then getting the data again.
Try:
$posts = getWallPosts($userid);
while($row = mysql_fetch_array($posts))
{
//Code to execute
}
Its an infinite loop. The expression in the while always executes so it will always be true.
You're returning a new result set each time the while statement executes. You should call getWallPosts first, assign it to $results, and then loop over it.
Related
Near the top of a PHP page I have a mySQL query followed by a do-while loop.
$query_offer = "SELECT offer, offer_text FROM ad_offers WHERE hid LIKE '$hid' AND show_from < CURRENT_DATE() AND show_to > CURRENT_DATE()";
$offer = mysql_query($query_offer, $MySQL_extranet) or die(mysql_error());
$row_offer = mysql_fetch_assoc($offer);
do {
SOME PHP STUFF
}while($row_offer = mysql_fetch_assoc($offer));
Then further down the page I want to repeat the same do-while loop with different PHP code inside it. But it doesn't work. It seems as if the system has forgotten the results of the query after doing the first do-while. If I precede the second do-while with a repeat of the original query, it works. But that seems very messy, and surely it is unnecessary to write the same query twice on the same page.
Any advice would be appreciated. Thanks.
Assign the rows to an array then reuse the array
$Offers = array();
while($row_offer = mysql_fetch_assoc($offer)) {
$Offers[] = $row_offer;
}
then further down your code loop over $Offers
after looping the data once, you need to do
mysql_data_seek($offer, 0);
More info: http://php.net/manual/en/function.mysql-data-seek.php
Note: This extension is deprecated as of PHP 5.5.0
Assign the results to an array and iterate over that again, or create function which you can call whenever you need it.
<?php
function getOffers($hid) {
$offers = array();
$query = mysql_query('SELECT ...');
while($offer = mysql_fetch_assoc($query)) {
array_push($offers, $offer);
}
return $offers;
}
$offers = getOffers($hid);
// use $offers here
// or here
// or recall getOffers($hid)
Anthony.
I made my scripts without class. (framework). Now I have changed my mind & I wanna make my scripts with classes. I like it. But there I have a problem.. Infinite Loop While. I didn't take this problem before with without classes..
While Rule;
while ($fetch=$db->fetchObject($db->q("SELECT * FROM auction_house.items ORDER BY id DESC LIMIT ".$min_stuff.",".$max_stuff."")))
{
// etc
}
Class;
public function fetchObject($queryRes)
{
$this->queryRes = $queryRes;
$this->record = mysql_fetch_object($this->queryRes);
return $this->record;
}
When I try to while loop, I am taking infinite loop on page.
How can I solve this problem?
You executing query in each iteration. It always returns a new resource.
Try to separate query and cycle:
$res = $db->q("SELECT * FROM auction_house.items ORDER BY id DESC LIMIT ".$min_stuff.",".$max_stuff."");
while ($fetch=$db->fetchObject($res))
{
// etc
}
Your code is executing on every while loop, so if you keep the $db->q nested there it will execute the query each time it loops, returning for each while iteration the first row of you query result.
try separating your code, like this:
$result = $db->q("SELECT * FROM auction_house.items ORDER BY id DESC LIMIT ".$min_stuff.",".$max_stuff."");
while ($fetch=$db->fetchObject($result)){
// etc
}
this way the $db->q() will only be executed once, as intended, and the while will loop trough its results.
You're starting a new query at each iteration.
You need to store your queryRes:
$queryRes = $db->q("SELECT * FROM auction_house.items ORDER BY id DESC LIMIT ".$min_stuff.",".$max_stuff."");
while ($fetch=$db->fetchObject($queryRes))
{
// etc
}
On an another side, I'm not sure you should store queryRes and record as instance variable of $db.
I am retrieving a couple of tables from a MSSQL database, which I am then running through to obtain order information from.
My code looks like this:
while($row = sqlsrv_fetch_array($orderResult))
{
......code........
..................
while($statusRow = sqlsrv_fetch_array($statusResult))
{
....code....
}
....code....
}
Now my problem is that after the second loop runs through, it never runs again. And I need it to run every time the first loop runs.
Is there anything I can do to reset that second loop to run again?
Thank you in advance. Any help or a push in the right direction will be very helpful.
Read about the other parameters in sqlsrv_fetch_array()
You can do something like this to reset
// reset, and get first row
$row = sqlsrv_fetch_row($result, SQLSRV_FETCH_BOTH, SQLSRV_SCROLL_FIRST);
// get second (and nth row) normally
$row = sqlsrv_fetch_row($result);
Alternatively, I think you could benefit from doing a JOIN in your query to return a single result. Merging results manually like this seems a little hackish.
I had a similar problem when calling a stored proc from a database that returned multiple result sets. I found Macek's answer didn't work for me, but another answer did:
$resultSet = array();
$isNotLastResult = true;
$i = 0;
while (!is_null($isNotLastResult))
{
$resultSet[$i] = array();
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$resultSet[$i][] = $row;
}
$isNotLastResult = sqlsrv_next_result($result);
$i++;
}
print_r($resultSet);
PS: I gave you an up arrow to counteract your down arrow. You asked a question I spent quite a bit of time looking for the answer to. Good question!
Use the following to reset the pointer:
sqlsrv_fetch_array ($Res, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_ABSOLUTE, -1);
Then use the same code as before to loop through the result set. sql_fetch_array appears to increment the pointer after retrieving the data. Requesting the -1 record retrieves nothing but then sets the pointer to 0 which is the first record.
are you sure your second loop got results for a second run ? maybe, if your $statusResult depents on your $row and your $row has just entries for the first loop you should insert some pseudo-entries to your db.
the second loop should refresh itself in the next "big" loop cause the whole inner block will be destroyed at the end of the big block and will be (fully) rebuild at the next entry.
I have a query that returns a few rows, and I have the following lines of code to retrieve them:
$result_set = mysql_query($query);
while($net_biz_sub_data[]=
mysql_fetch_array($result_set,MYSQL_ASSOC));
My question is what is the right way to retrieve that db query data without getting the last array empty ?
When I count() it is always num of rows + 1, and I would like to correct that.
Because of the way the while loop works, you should do
while($dataz = mysql_fetch_assoc($result_set))
{
$net_biz_sub_data[] = $dataz;
}
Use
$result_set = mysql_query($query);
while($net_biz_sub_data = mysql_fetch_assoc($result_set)){
//use $net_biz_sub_data here
}
I have a mysql query:
$a=mysql_query("SELECT id FROM table1 WHERE p2='fruit' LIMIT 1");
This will only ever return one result or none.
I'm trying to first count the results, then if it 1, to pass the returned id to a variable.
Question: If I do
$results=count(mysql_fetch_assoc($a));
to count the number of rows returned, can I still do later
while($row = mysql_fetch_array($a)){
$id=$row['id'];
}
or will the first delete the array somehow???
Is their a better way to do all this?
You really not need to do anything if there is one row or null
Consider below code it will set id value if there is 1 row fetched otherwise it will be null
$id=''
while($row = mysql_fetch_array($a)){
$id=$row['id'];
}
No count needed.
$results=count(mysql_fetch_assoc($a));
does not count the number of rows as mysql_fetch_assoc returns one row. I believe you're looking for mysql_num_rows:
$results = mysql_num_rows($a);
$num_rows = mysql_num_rows($a);
You can then do an IF statement on this and later do a while loop on the fetched array
Have you tried mysql_num_rows ??
http://php.net/manual/en/function.mysql-num-rows.php
What happens when using:
while($row = mysql_fetch_array($a)){
$id=$row['id'];
}
it is just like reading a file,every time mysql_fetch_array($a) is called the next line is parsed untill it reaches the end of the file. A cursor of some sort is known in the background. Meaning that if you would enter by hand
//backgroundCursor = 0
$row = mysql_fetch_array($a)
//backgroundCursor = 1
$row = mysql_fetch_array($a)
//backgroundCursor =2
$row = mysql_fetch_array($a)
//backgroundCursor = 3
The while instruction just automates the stuff.
mysql_fetch_array increases the background cursor at every call so if you call it twice it will not give you the same line.
To get a clear view on this read something about reading from a file line by line.
No you cannot as each call to mysql_fetch_assoc() loads a new row, if there is any. You could indeed assign both variables at once:
$results=count($row = mysql_fetch_assoc($a));
but
But mysql_fetch_assoc($a)) returns false and as the result of count(false) is 1 this will not tell you anything. Besides, if there is no row all you really need is $row = mysql_fetch_assoc($a) and test if ($row) {...}.