Hello, I was wonder how I would use a PHP query twice. Right now, the second result is just blank, with no errors. I know there is some kind of reset that can be performed on querys and I just cant remember it. I have searched Google and multiple forums but I can't find anything. Thanks,
Are you referring to a mysql query in php? If you use the enhanced extension (mysqli) you can use clone to preserve another copy.
Yes, for example I have a query that runs inside a while statement: while (example conditions) { $data5 = mysql_query("SELECT price FROM menu WHERE id ='$i") or die(mysql_error()); $myrow5 = mysql_fetch_array($data5); echo $myrow5['price']; } Code (markup): So the above code will work for only the first record, then every record after that only has a blank price.
IF you're done with the first query you need to make sure to mysql_free_result($data5); Code (markup): before calling the query and using that resource handler again. freeing the result isn't needed for INSERT and UPDATE type of queries.
Depending your condition there may be a way to do that in one call instead of looping. For example $data5 = mysql_query("SELECT price FROM menu") or die(mysql_error()); if ($data5) { $num_results = mysql_num_rows($result); } else { $num_results = 0; } if ($num_results > 0) { for ($i=0; $i <$num_results; $i++) { $row = mysql_fetch_array($result); echo $row['price']; } mysql_free_result($result); } Code (markup):
When you say "twice" do you mean query different tables for different results ? $sql = "SELECT * FROM table1, table2, table,3"; $result = mysql_query($sql) or die("MySQL error!"); $rs = mysql_fetch_array($result); Code (markup): Then you print or echo $result // or whatever
@kblessinggr Doesnt mysql_free_result($data5); just free up the memory usage? It didnt work for resetting the query, I still just get a blank. @pixmania I just want to run a mysql query in a while loop ($myrow5 in my example).
what is the while conditions anyways? Its possible they're triggered after only 1 loop. Did you note the alternative way of doing it, getting it in one query instead of multiple queries.
You can reset a query using mysql_data_seek($query,number_of_record_to_start_with); For instance, like this: $query = mysql_query("SELECT * FROM $table WHERE $column_name = $condition"); //php code goes here //and then you want to use the query again, starting from the first record in the result mysql_data_seek($query,0); PHP:
You do want to run mysql_free_result() because it's good practice. If your only WHERE condition is an ID, fetch all of the data you need in one query. There's no reason to run five (or however many) queries unless the result set is huge (in which case you should be optimizing in other ways).