While Loop - PHP - php

I've got a few while loops in my PHP code that look somewhat like this:
qry_myquery = "SELECT * FROM table WHERE value = '$value' ";
$rs_myquery = mysql_query($qry_myquery) or die(mysql_error());
while($row = mysql_fetch_assoc($rs_myquery)){
if($row[$entryType] > 0){
$entryPointNumber = $row[$entryType];
}else {
$data["FatalError2"] = "Error!";
die();
}
} //END: While loop - entries from AJAX legal.
My question - is there anything wrong with writing while loops in this way? Will they continue to run indefinitely and suck memory/unneeded processing power? Am I supposed to close them off somehow after I'm done with them?

is there anything wrong with writing while loops in this way?
no
Will they continue to run indefinitely and suck memory/unneeded processing power?
no, it runs as long as the condition is true, in your case, when there are no more rows, the loop will stop
Am I supposed to close them off somehow after I'm done with them?
no (but maybe i didnt understand what you are asking here)

The WHILE loop seems to be fine and the loop wont run indefinitely.
But I see one issue with the code, which is the die() statement.
By calling the die(), you are not doing a clean exit in the code.
What I mean is you are not closing the database connect.

Related

What does for(;;) do?

I have to maintain a code, and came up with this:
for (;;) {
//code
}
What would it do? I couldn't find documentation about it.
In a hunch I think it runs only once... but that would be useless...
it is an infinite loop, similar in function as:
while(true)
{
}
Your code sample is an infinite loop. To terminate, the omitted code (//code) must exit the loop or the entire PHP script.
It's a for loop without initialization parameters, no breaking conditions and no increments/decrements/whatever on each iteration - think of it like for (nothing; nothing; nothing).
Unless you break it from the inside, it's going to run forever.
For embedded code it is the main loop that does all the other sub process in a super loop scheme.

Using mysql_fetch_assoc twice in a single PHP script

I usually try to minimize calls to MySQL where possible, but I've finally encountered the case where I have to do multiple calls to MySQL in a single script.
It looks like you can't use mysql_fetch_assoc twice in a single script(!).
It seems that mysql_data_seek is the solution, but I cannot seem to get it to work.
To be clear, I have two queries I need to make. The second query depends on results from the first... Here's the structure:
$result = mysql_query($query1);
while($row = mysql_fetch_assoc($result)){
$pos = $row['position'];
}
mysql_free_result($result); // result freed per comment below.
$query2 = ' '; //... dependent on $pos - in mysql shell this returns results!
$result2 = mysql_query($query2)
while($row = mysql_fetch_assoc($result2)){
echo $row['id'];
}
What happens above is that the second while loop returns no results even though the query should have nontrivial rows.
Just to be sure:
Is this how you clear the pointer from the previous result to be able to use mysql_fetch_assoc again?
mysql_data_seek($result,mysql_num_rows($result) - 1);
I'm not sure what to use as the second argument. Admittedly, I am not that clear on pointers, but it seems I should clear the pointer to 0. But I get this error:
Offset 0 is invalid for MySQL result index 8 (or the query data is unbuffered
Check your connection with mysql_error() and see if you're getting the "commands out of sync" error. If so, you need to call mysql_free_result() after completing the first query and before starting the second. You could also just call mysql_close() to close your database connection and then reopen a new one.
For more details, see this question.
OP changed the question, so see the edit
*Deleted the posted codes here**
EDIT
After your edited your question and made clear you have actually 2 resources it looks like there is something else wrong. You don't have to worry about pointer when you use two different resources to supply mysql_fetch_assoc(). The thing with mysql_fetch_assoc() is that it takes your param ($result) by reference.
Now to answer your question:
I usually try to minimize calls to MySQL where possible, but I've finally encountered the case where I have to do multiple calls to MySQL in a single script.
Nothing wrong with multiple SQL calls in one script. Although in general you should try to minimize the SQL calls (because they may hurt performance).
It looks like you can't use mysql_fetch_assoc twice in a single script(!).
Plain wrong. Ofc you can do it. As long as you note the above. However when you have two result sets this wouldn't be your problem.
It seems that mysql_data_seek is the solution, but I cannot seem to get it to work.
Again: this has nothing to do with it when you use two (different) result sets.
To be clear, I have two queries I need to make. The second query depends on results from the first.
This shouldn't be any problem at all. It looks like is something else wrong. Have you verified that the second query really is what you think it is? Are you sure there are records? Are you sure there aren't any (MySQL) errors. Do you have error reporting enabled? Have you tried printing out mysql_error()? To better be able to help you can you please provide your real code and not etc etc stuff? Maybe something else is going on.
Or maybe you are simply trying to run the second query inside the first loop. Which would be bad in so many ways.

Is a mysql query always executed even if it is in a php if?

Just wondering. Say I have this in a php page
<?php
if x {
$query = mysql_query(etc)
}else{
$query2 = mysql_query(etc)
}
?>
Lets say X = true then $query is executed, but is $query2 completely ignored? (so also not executed in the background?)
Thanks
anything within the "else" bracket will not be executed unless the condition is false. Not even "in the background". PHP will completely ignore it as if it didn't exist.
Yes. Lines that are bypassed in a control structure are not executed.
you know, that's the point of the conditional statement.
If it was executing both statements, there would be no sense in having it at all.

When are do loops useful?

As you all probably know, do loops execute at least once, even if the statement is false — while the while loop would never execute even once if the statement is false.
When are do loops useful? Could someone give me a real life example?
They're basically useful when you want something to happen at least once, and maybe more.
The first example that comes to mind is generating a unique ID (non sequentially) in a database. The approach I sometimes take is:
lock table
do {
id = generate random id
} while(id exists)
insert into db with the generated id
unlock table
Basically it will keep generating ids until one doesn't exist (note: potentially an infinite loop, which I might guard against depending on the situation).
The Do loop is very powerfull if you have to check multiple files etc. Due to the guarentee of iteration it will work all the way through.
do {
if($integer > 0) { $nameoffile[0]++; }
else { $nameoffile[0] = $nameoffile[0].$integer; }
$integer++;
} while(file_exists("directory/".$nameoffile[0].".".$nameoffile[1]));
Next to what has already been answered, you can do crude stuff like this with a do:
do
{
if ($cond1) break;
if ($cond2) continue;
do_something();
} while(true/false);
Which is a modification of a switch loop, which allows continue. You can simulate goto similarities in case goto is not available and similar.
It must not make your code more readable, so it's often not suggested to do that. But it technically works.

php mysql 2 different ways

I recently ran across some code which the person did the first one. Would like some thoughts on if the top one is better or why a person would write it that way? Any positive reasons over the bottom way.
$result = mysql_query($query)or die("Obtaining location data failed!");
for ($i = mysql_num_rows($result) - 1; $i >=0; $i--)
{
if (!mysql_data_seek($result, $i))
{
echo "Cannot seek to row $i\n";
continue;
}
if(!($row = mysql_fetch_object($result)))
continue;
echo $row->locationname;
}
mysql_free_result($result);
vs
$result = mysql_query($query) or die("Obtaining location data failed!");
while($row = mysql_fetch_object($result)){
echo $row->locationname;
unset($row);
}
mysql_free_result($result);
It looks like the top code is iterating through the mysql result backwards, where the first one is going through it forwards.
The second code example looks cleaner, and there is probably a way to adjust the query to get the results in reverse order in the first place, instead of the somewhat convoluted way the top loop was performed.
Those two are not equivalent since only the first processes the result set in reverse order.
I'd do that with an ORDER BY x DESC clause if only to keep the code simple. When using mysql_query() the complete result set is transferred from the MySQL server to the php process before the function returns and mysql_data_seek() is only moving some pointer within the process' memory, so performace-wise it shouldn't matter much. But if you at some point decide to use an unbuffered query instead it might very well affect the performance.
Definitely the second one :
less code = less code to maintain =~ maybe less bugs !!
The top one has definite advantages when it comes to job security and 'lines of code' performance metrics. Apart from that there is no good reason to do what they did.

Categories