I am trying to display posts in a specific condition with a while loop but it is giving me a 30 second timeout error. Here's my code:
while ($tagrow = mysql_fetch_assoc(mysql_query("SELECT * FROM posts WHERE tag='$usersearch' ORDER BY id DESC"))) {
$stufftoecho .= $tagrow['text'];
}
There is a timeout error on the line with the while loop, I guess it is an infinite loop but I don't know how to fix it.
NOTE: Please don't tell me I need to use mysqli or PDO, i will convert to one of them later.
Run mysql_query() once out of while loop.
$sql = "SELECT * FROM posts WHERE tag='$usersearch' ORDER BY id DESC";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row['text']; }
mysql_free_result($result);
This of course is going to be an infinite loop, provided at least one element matches the query; I suspect that in your infinite loop, you never progress past the first element returned by the query.
while ($tagrow = mysql_fetch_assoc(mysql_query("SELECT * FROM posts WHERE tag='$usersearch' ORDER BY id DESC"))) {
The function mysql_fetch_assoc is going to take in a result set of a query, and iterate through it, returning the next element in the series each time it is called.
The function mysql_query is going to take a query and return a result set;
They way you have your while loop structured, you will be executing the query, and passing the result set directly into the fetch_assoc, which will inturn assign the value of $tagrow to the first element; and then do it again, and again.
What we need to do instead, is execute the query, and then save the result set. This makes it so you only need to execute the query once, instead of on each iteration, and save the results in memory.
We can do this by simply breaking it into the following two lines, and using a variable as temporary storage of the query results.
$results = mysql_query( "SELECT * FROM posts WHERE tag='$usersearch' ORDER BY id DESC" );
while ( $tagrow = mysql_fetch_assoc( $results ) ) {
I'd suggest you to break it up into chunks.
$query = mysql_query("SELECT * FROM posts WHERE tag='".$usersearch."' ORDER BY id DESC") or die(mysql_error());
while ($tagrow = mysql_fetch_assoc($query)) {
$stufftoecho .= $tagrow['text'];
}
Hope this helps.
Peace! xD
It seems your running the query every time it goes through the loop. Try this instead,
$result = mysql_query("SELECT * FROM posts WHERE tag='" . $usersearch . "' ORDER BY id DESC"); //execute query
if ($result)
{
while ($tagrow = mysql_fetch_assoc($result))
{
$stufftoecho.= $tagrow['text'];
}
}
else
{
echo mysql_error();
}
Related
I have this bit of code that doesn't produce anything, not even an error message. I'm trying to echo the result inside the while loop, but even that doesn't show anything. Any tips?
foreach($droppedStudentIds as $value){
$query3 = "select * from student_classlists where StudentId = '$value' and ClassListDate = (select max(ClassListDate) from student_classlists)";
if($result = mysqli_query($mysqli, $query3)) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "Date: ".$row['ClassListDate'];
$droppedStudentIds[$value][] = $row['ClassListDate'];
}
mysqli_free_result($result);
} else die ("Could not execute query 3");
}
My goal is to look up a date information for each element inside the $droppedStudentIds array. I checked the MySQL query in itself and it produces that desired result.
Thanks!
You're assigning to the array you're looping through on this line:
$droppedStudentIds[$value][] = $row['ClassListDate'];
This could be causing your script to timeout, which would be why you're not seeing any output.
I'd add a second array to avoid conflicts and use that for storing results from the query, e.g.
$temp[$value] = $row['ClassListDate'];
Thanks all for the response, it helped pin down the mistake!
No need for a while loop when asking for a single record
The query was actually incorrect. The subselect was getting the maximum date in the database, regardless of whether the StudentId was present or not. The correct query is the following:
select ClassListDate from student_classlists where StudentId = '$value' and ClassListDate = (select max(ClassListDate) from student_classlists where StudentId = '$value')
Thanks again!
How do I show the results for $wordavg in php. I have done the query in SQL on database after taking out variables so I believe the query is correct but don't know how to show the results of the search in php.
$usertable = 'words';
$yourfield = 'wordname';
$query = "SELECT AVG(CHAR_LENGTH( wordname)) AS $wordavg FROM $usertable WHERE $yourfield LIKE '"."$current_letter"."%' ";
$result = mysql_query($query);
First, you should be using mysqli instead. Back to your question, usually you can iterate over a result with a loop as follows:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field'];
}
More info and examples in the PHP mysql_query doc.
Since you only have one row of data to return, you don't need the loop part. You can simply use
$row = mysql_fetch_assoc($result);
$wordavg = $row['wordavg'];
You shouldn't have the $ in wordavg in your query. It should be just ...AS wordavg FROM...
If I only have one row that I'm getting through
$sql = mysql_query("SELECT id,user,comments FROM user WHERE id='15' AND user = '15'");
is there a way to just get the comments from that one row without going through a while loop :
while($row = mysql_fetch_array($sql)){
$comments = $row['comments'];
}
Is there something similar besides using a while loop? If my data has thousands to millions of data, a while loop will take a long time? Is this a more logical way to locate a certain row and reduce its speed?
Thanks for your help!
If you're only returning one row then only fetch once.
if ($row = mysql_fetch_array($result))
{
$comments = $row['comments'];
}
$sql = mysql_query("
SELECT id,user,comments
FROM user
WHERE id='15'
AND user = '15'
LIMIT 1");
The LIMIT 1 will stop the query after the first result
when you have more than one rows in resultset, then and then only you need to do it in loop else to fetch single row you are not required to put result set in loop.
you can do it like this..
if(mysql_num_rows($result) == 1){
if($row = mysql_fetch_array($result)){
$comments = $row['comments'];
}
}
I encounter some problem where i want to execute a SQL statement and get the total number of records + all the records.
$strSQL = "SELECT * FROM table WHERE ProjectID = 1 ";
$stmt = $db->query($strSQL);
$total = count($stmt->fetchAll());
while ($row = $stmt->fetch()){
..No More Record Shown here..
}
but there is no more record in the while loop after i execute fetchAll, i believe I need to get back to the first row or something, anyone know how to fix this?
You've already fetched all the records with fetchAll(). So when you call fetch(), there are no more records to read. Try storing the return value of fetchAll() in a variable and iterating through that. Something like this:
$strSQL = "SELECT * FROM table WHERE ProjectID = 1";
$stmt = $db->query($strSQL);
$allRows = $stmt->fetchAll();
$total = count($allRows);
foreach ($allRows as $row){
// process each $row
}
I have the following code:
$sortorder = $_GET['sort'];
switch($sortorder)
{
case "modulea":
$result2 = db_query("SELECT * FROM {vanqueue_registrations} WHERE isactive=1 ORDER BY `cleanmodule` ASC");
case "moduled":
$result2 = db_query("SELECT * FROM {vanqueue_registrations} WHERE isactive=1 ORDER BY `cleanmodule` DESC");
case "typea":
$result2 = db_query("SELECT * FROM {vanqueue_registrations} WHERE isactive=1 ORDER BY `cleantype` ASC");
var_dump($result2);
case "typed":
$result2 = db_query("SELECT * FROM {vanqueue_registrations} WHERE isactive=1 ORDER BY `cleantype` DESC");
default:
$result2 = db_query("SELECT * FROM {vanqueue_registrations} WHERE isactive=1");
}
while($result = mysql_fetch_assoc($result2))
{
var_dump($result);
$value .= "<tr><td><center>" . $result['cleanmodule'] . "</center></td><td><center>" . $result['cleantype'] . "</center></td><td><center>" . $directions[$result['direction']] . "</center></td></tr>";
}
As you can see, it takes a GET variable and, depending on its value, executes a certain query. (Don't worry, this is only testing code, I'll obviously validate the input more later.)
My problem: the correct query is executing, but mysql_fetch_assoc seems to be reordering the rows in a way I don't want.
I 'm testing with the case typea, and when I execute the page, that call to var_dump is executed - I can see the result on the page. So the switch is definitely working.
But, the var_dump inside the while statement is outputting the rows ordered by the primary key in the table, not by, per my request, cleantype.
How can I make mysql_fetch_assoc output the rows the way I want them ordered?
TIA.
You forgot to use break at the end of all your cases...
Therefore, your default query always got executed at last.