PHP Infinite Loop "While" with Class - php

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.

Related

Checking database with Recursive Function

i'm trying to do a recursive function. It's a simple id creation and checking the id inside the database. If the id is already created, then it should run the function back to create a new id and do the checking again. Below is the code.
public function session_order(){
$sr_function = new sr_function();
$session_no = (rand(0,2));
//i have set the order_id in the db as '1'//
$sql = "SELECT COUNT(order_id) as order_count
FROM src_order WHERE order_id = '".$session_no."'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
if ($row['order_count'] == 1){
$this->session_order();
}
return $session_no;
}
how ever, when $row['order_count'] == 1, the function did not run the session_order() back to create another session no. Thank you
When you generate a successful ID, you need to pass it back up the call stack.
if ($row['order_count'] == 1){
$session_no = $this->session_order();
}
Why are you doing this with recursion? A simple iterative loop seems more reasonable. For one thing, the current implementation repeats the DB query for every ID creation. Isn't the query result supposed to be the same every time? Or are you altering the ID list in parallel?

PHP Use for loop to iterate over MySQLi recordset

Whenever I am working with PHP MySQLi recordsets, I have always worked with the returned data using the standard while loop to iterate over the recordset. Recently, however, I started wondering if there is a way to use a for loop instead. This would be handy in situations where you want to limit the number of results returned.
Here is an example of using the while loop:
//Prepare a query that will produce a reverse-order recordset
$sql = "SELECT * FROM tblNames ORDER BY numberID DESC";
$recordset = $conn -> query($sql);
//Count the number of contacts added to the list
$contactCount = 0;
while($row = $recordset -> fetch_assoc())
{
//If the list has reached its maximum number (5), end the display loop
if($contactCount >= 5)
{
break;
}
$contactList .= $row["name"] . "<br>";
//Increment the number of contacts added to the list
$contactCount ++;
}
//Use '$contactList' somewhere....
echo($contactList);
While this definitely works, there must be a better way to end the loop after a specified number of iterations. Is it easier to use a for loop in a situation like this? If so, how?
You can use LIMIT in the query. For example:
SELECT * FROM tblNames ORDER BY numberID DESC LIMIT 15
This way you don't have to worry about what happens if your query does return less than 15 results.
As I was writing this question, I suddenly decided that I would try it one last time, but in a different way than I had been previously. I had been stuck finding an efficient/safe way to tell when the recordset was empty (had been running into issues when the custom max number was greater than the number of records, and when there were no records).
//Execute the SQL query (reverse order), and store the results in a recordset
$sql = "SELECT * FROM tblNames ORDER BY numberID DESC";
$recordset = $conn -> query($sql);
//Use a 'for' loop to iterate over the recordset
for($i = 0; $i < 15; $i++)
{
//If there is another row in the recordset, add the column value to the list
if($row = $recordset -> fetch_assoc())
{
$contactList .= $row["name"] . "<br>";
}
else
{
//Break from the loop when there are no more records (used if the
// given maximum number was actually greater than the number of records)
break;
}
}
echo($contactList);
As far as I can tell, this is a much better way to loop through a set/custom number of records, and then stop. It also will safely catch the end of the recordset (assuming it is reached before the cutoff number), and end the loop.
Edit
As is pointed out in the answer by HenryTK above, if you have control over the query, the best way is to use the LIMIT SQL statement. However, if you merely have access to the recordset, I still think the for loop will save time. (Although I'm not sure when this would happen).

while loop mysql/PHP exceeds execution time

This while loop causes a Fatal error: Maximum execution time of 30 seconds exceeded.
The query IS working. I tested the query in phpmyadmin.
Nothing is inside the loop in order to test whether it's content caused the error.
It looks like the while loop is overloading. It seems that the script takes too long to load (thinking the query is too extended), not seeing any possibilities the loop to be infinite.
while($tags_db = mysqli_fetch_array(mysqli_query($link,
"SELECT *
FROM zk_terms
WHERE parent_id = 1 AND parent_type = 'archive' AND taxonomy = 'tag'"))){
}
You're re-executing the query every iteration, and then mysqli_fetch_array is fetching only the first result each loop. You have to move mysqli_query outside the loop and assign it to a variable.
You need to modify your code:
$query = mysqli_query($link,
"SELECT *
FROM zk_terms
WHERE parent_id = 1 AND parent_type = 'archive' AND taxonomy = 'tag'");
while($tags_db = mysqli_fetch_array($query)){
// your code
}
Place your mysqli_query command outside your while and catch the result in a variable. Then use the variable with mysqli_fetch_array in the while .
otherwise, everytime the while condition is examined, the query is run again

PHP - Why while(mysql_fetch_array(mysql_query())) loops?

So I have the code:
$sql = "SELECT * from users WHERE level = 2";
$result = mysql_query($sql);
while($write = mysql_fetch_array($result)){
echo ''.$write['username'].'';
}
I want to make it more simple so I do:
while($write = mysql_fetch_array(mysql_query("SELECT * from users WHERE level = 2"))){
echo ''.$write['username'].'';
}
Why the first code isn't infinity looping and the second code is?
the first code iterates a resource given by mysql_query($sql);
the second iterates the query and loads the first row each time forever.
so instead of going to the next row, it makes a new query and starts on that row.
As a side note - dont use mysql_* functions. Use mysqli_ or pdo instead.
It is because your query is inside which tells the while to execute the query again and again. If you are looking for a much simpler alternative, you can try using an ORM such phpactiverecord.

mysql_fetch_array() timing out

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.

Categories