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.
Related
I'm trying to create a while loop in PHP which retrieves data from a database and puts it into an array. This while loop should only work until the array its filling contains a certain value.
Is there a way to scan through the array and look for the value while the loop is still busy?
to put it bluntly;
$array = array();
$sql = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($sql)){
//Do stuff
//add it to the array
while($array !=) //<-- I need to check the array here
}
You can use in_array function and break statement to check if value is in array and then stop looping.
First off, I think it'd be easier to check what you're filling the array with instead of checking the array itself. As the filled array grows, searching it will take longer and longer. Insted, consider:
$array = array_merge($array, $row);
if (in_array('ThisisWhatIneed', $row)
{
break;//leaves the while-loop
}
However, if you're query is returning more data, consider changing it to return what you need, only process the data that needs to be processed, otherwise, you might as well end up with code that does something like:
$stmt = $db->query('SELECT * FROM tbl');
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if ($row['dataField'] === 'username')
{
$user = $row;
break;
}
}
WHERE could help a lot here, don't you think? As well taking advantage of MySQL's specific SELECT syntax, as in SELECT fields, you, need FROM table, which is more efficient.
You may also have noticed that the code above uses PDO, not mysql_*. Why? Simply because the mysql_* extension Is deprecated and should not be used anymore
Read what the red-warning-boxes tell you on every mysql* page. They're not just there to add some colour, and to liven things up. They are genuine wanrings.
Why don't you just check each value when it gets inserted into the array? It is much more efficient than iterating over the whole array each time you want to check.
$array = array();
$stopValue = ...
$sql = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($sql)){
array_push($array,$row['column']);
if($row['column'] == $stopValue){
// The array now contains the stop value
break;
}
In this script, I basically want to echo out data from a mysql table when the certain row record matches the name in browser address bar. But for some reason, no data is echoed. Any reason my while loop doesn't work?
$users = $_GET['username'];
$other_friend_query = mysql_query("SELECT * FROM friend WHERE RelatingUser='$users'");
$other_friend_assoc = mysql_fetch_assoc($other_friend_query);
while ($other_friend_assoc = mysql_fetch_assoc($other_friend_query)) {
$friend_related = $other_friend_assoc['RelatedUser'];
echo $friend_related;
}
That's because you call mysql_fetch_assoc before your while loop. When you call this, it fetches a result. Then when you go to your loop, that result has already been fetched. Just remove that and you'll be good to go. As stated in the comments, stop using mysql_ functions. The code below will escape your posted variable and also check for errors. It's also better practice to use a column list, instead of SELECT *.
$users = mysql_real_escape_string($_GET['username']);
$other_friend_query = mysql_query("SELECT * FROM friend WHERE RelatingUser='$users'") or die( mysql_error() );
while( $other_friend_assoc = mysql_fetch_assoc($other_friend_query) ) {
$friend_related = $other_friend_assoc['RelatedUser'];
echo $friend_related;
}
Any reason my while loop doesn't work?
May not be the only reason, but you're skipping the first result.
// the following line is unused and therefore unnecessary
$other_friend_assoc = mysql_fetch_assoc($other_friend_query);
while ($other_friend_assoc = mysql_fetch_assoc($other_friend_query)) {
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.
Is there a PHP function to get the full result with a mysql query in a multidimensional array?
SELECT * FROM table
Usually I would make something like this:
$query = mysql_query = ("SELECT * FROM table");
while ($result = mysql_fetch_array($query){
echo $result[0];
}
You can create your own function like mysql_fetch_array_complete() and imagine that it's builtin ;-)
If you are using PDO to access mysql there is.
http://www.php.net/manual/en/pdostatement.fetchall.php
Otherwise you need to do it yourself.
$query = mysql_query = ("SELECT * FROM table");
$all_results = array();
while ($result = mysql_fetch_array($query){
$all_results[] = $result;
}
print_r($all_results);
The $all_results variable will be a multi-dimensional array with all the records.
You could always write your own function to do this, but it would often lead to an unnecessary iteration through the result set (once when you call your function, another time when you actually USE the resulting array).
Since you're in php5, you could create a database result class that implements the Iterator interface. Then, you can use your class in foreach () loops and have much of the ease-of-use that you get from an array.
As of PHP 5.3 there is a built in function:
fetch_all
I have this method in my db class
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
$results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
return mysql_num_rows($results) > 0 ? mysql_fetch_assoc($results) : false;
}
This works great for queries that return 1 row, but how can I get an array returned something like this?
$array[0]['name'] = 'jim'
$array[0]['id'] = 120
$array[1]['name'] = 'judith'
$array[1]['ID'] = 121
Now I know I could use a while loop to insert this data into the array like so, but I was wondering if PHP could do this with an internal function? I havn't been able to find on the docs what I'm after.
The reason I don't want to run the while within the method is because I am going to reiterate back over the array when it's returned, and I'd rather not run through the results twice (for performance reasons).
Is there a way to do this? Do I have a problem with my general query method design?
Thank you muchly!
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
$results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($results))
{
$data[] = $row;
}
return $data;
}
this will always return an array.
EDIT:
I didn't read the question well.
If you realy don't want to use the loop then I would do this:
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
return mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
}
then loop over it, however I would just use the loop.
You might also want to look at the PDO extension. You can load the entire result set into an array or you can loop using foreach.
<?php
$db = new PDO($connection_string, $username, $password);
$result = $db->query($queryString);
foreach($result as $row) {
// do something
}
// or
$result = $db->query($queryString);
$result_array = $result->fetchAll(PDO::FETCH_ASSOC);
?>
Most people use a while() loop in the query to do exactly what you want and then loop over the array to process it.
However, you're right: it wastes memory, which could be a problem with a large dataset. An alternative is for your query method to return the resultset resource. Then your while loop can use that to fetch each row as it requires it.
To abstract that away, I would suggest another class to do that for you. Then your query call would return a new instance of that class which has the MySQL resultset resource as an instance variable and packages up the mysql_fetch_assoc() call.
Look at PEAR::MDB2 (Quickstart Cheatsheet). It provides lots of different functions for doing something like this. It also does not tie you down into using MySQL specific functions because it is a database abstraction layer.
$result = $db->queryRow($query, MDB2_FETCHMODE_ASSOC);
There are other abstraction layers such as ADO as well.
thanks for the ideas. I have a function that returns an associative array from the sql (used in Moodle).
$results = get_records_sql($sql);
//to create a numerically indexed array:
$data = array();
foreach ($results as $row)
{
$data[] = $row;
}
return $data;
}