I'm making a PHP to check for the friends ID in a friends relation table, then returns the info of the friends.
The problem is, the first loop loops 2 times, and that's right, when I check for the value of the count of the second loop, I find it equals to 4, how can this happen and the second table got 4 rows?
Here's the code:
while ($rowres = mysql_fetch_array($listres))
{
if ($_GET["ID"] == $rowres["ID"])
{
while ($row = mysql_fetch_array($result))
{
$count++;
if ($rowres["FID"] == $row["ID"])
{
}
}
}
}
the inner loop will loop through result only one loop, because after it loops to the last element of $result pointer of result will be point after last element, the easiest way here will be probably reset pointer to the top:
while ($rowres = mysql_fetch_array($listres))
{
if ($_GET["ID"] == $rowres["ID"])
{
mysql_data_seek($result,0); //<-HERE
while ($row = mysql_fetch_array($result))
{
$count++;
if ($rowres["FID"] == $row["ID"])
{
}
}
}
}
please note: mysql extension is DEPRECATED and will be removed in the future. Instead use mysqli or PDO
Related
I have this situation:
while ($row = pg_fetch_row($result)) {
if ($this_is_last_row == TRUE) {
echo 'yes this is last row';
} else {
echo 'no, there is more rows';
}
}
Is it possible to check each row on 'while' loop whether it's the last row or not, without knowing number of rows first?
easy:
$last = false;
while ($row = pg_fetch_row($result)) {
$last = $row;
}
if ( $last !== false )
{
// this is the last row:
}
There is no other way as stepping through the entire result set and hold the record. The remainder will be the last, or false if there are no records.
As usual, the result set does not know how many rows are in the back. ...fetch_all(...) may end in a memory overflow when there are to many records.
A similar question was asked here
Looks like you can retrieve the number of rows and then just compare your current against that (maybe keep a count of your iteration and use that as the row number).
$number = mysql_num_rows($sql);
edit: in your case it looks like you'd want to use: pg_num_rows
Oh, just improvise:
$curr = pg_fetch_row($result);
while ($curr) {
$next = pg_fetch_row($result);
if ($next) {
echo 'no, there is more rows';
} else {
echo 'yes this is last row';
}
// use $curr anywhere _before_ this line
$curr = $next;
}
$result = mysql_query($strSql);
foreach($bestmatch_array as $restaurant)
{
while($row = mysql_fetch_array($result))
{
if($restaurant == $row[0])
{
$value = $row[1];
}
}
}
What I am trying to do is sort the result of array formed by query according to the values stored in $bestmatch array.
I don't know what I am doing wrong but the 4th line just seems to run once. Please help guys. Thanx in advance.
php mysql_fetch_array() not working as expected
Your expectation is not right.
foreach($bestmatch_array as $restaurant)
{
// This loop will only run for first iteration of your foreach.
while($row = mysql_fetch_array($result))
{
}
// everything has been fetched by now.
}
That is a logically incorrect sequence.
You expect your inner loop to be called over and over again as many times as you have the outer loop run but record fetch does not work like that. For outer loop's first run all the rows in $result will be fetched and since you do not reset the counter after your while loop that means after the first run there will be no more rows for the next run.
Solution? Fetch the row from mysql first then use a simple in_array call to check whether that restaurant is there in your array.
$result = mysql_query($strSql);
while($row = mysql_fetch_array($result))
{
$name=$row[0];
if(in_array($name,$bestmatch_array))
$value=$name;
}
Store the results of the query in the array first:
$result = mysql_query($strSql);
$results_row = array();
while($row = mysql_fetch_array($result))
{
$results_row[] = array($row[0],$row[1]);
}
foreach($bestmatch_array as $restaurant)
{
foreach ($results_row as $key => $value)
{
if($restaurant == $results_row[$key][0])
{
$value = $results_row[$key][1];
}
}
}
I loop trough the rows with this code:
while ($row = $result->fetch_assoc()) {
//...
}
But how is it possible before the mysqli_fetch_assoc to check if there will be a next record, or not? I mean, like: $result->hasNext()
Check the total number of returned rows using $mysqli->num_rows, then compare it to a counter in your loop that you increment with each loop iteration.
$row_cnt = $result->num_rows;
$loop_ct = 0;
while($row = $result->fetch_assoc()) {
if(++$loop_ct < $row_cnt) {
//do something
}
}
I prefer working efficiently and don't write extra code if it isn't needed. The following will work just fine:
$cnt = $result->num_rows;
while($row = $result->fetch_assoc()){
//....
$cnt--;
if($cnt == x){ //Where x is the number you want
//....
}
}
You're doing a while loop until you don't have any rows left, so the question is do you really need a test or do you just run the code you want at the end of your loop? If you need to test inside whether there will be a next row, you could do this:
$row = $result->fetch_assoc();
while (1) {
...
if (!$row = $result->fetch_assoc()) {
// No next row
break;
}
}
Which is pretty similar to what you're doing now.
Consider the code you posted
while ($row = $result->fetch_assoc()) {
//...
}
It is already doing that. check out the docs for mysqli_result::fetch_assoc, the while loop will break if $result->fetch_assoc() returns NULL. You don't need to manually check anything.
Either you can go with #McWayWeb or you can try this function mysqli_next_result().
Read it's manual here:- http://php.net/manual/en/mysqli.next-result.php
This question already has answers here:
Mysqli query doesn't work twice
(2 answers)
Closed 5 years ago.
I'm retrieving some data from a mysql database. There are two loops which uses the same result set.
while ($row = mysqli_fetch_array($newsQuery)) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
This loop ends with success. then in the same page I have the following loop.
while ($row = mysqli_fetch_array($newsQuery)) {
echo $row["news_content"];
}
This loop doesn't return anything even if there are content in the table. When I try it in the first loop. the content is displayed correctly. Any idea on what I'm doing wrong.
From PHP's mysqli_fetch_array DOCS:
Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.
You are using a 'while' loop on $row = mysqli_fetch_array($newsQuery)
This means the loop will keep going untill mysqli_fetch_array($newsQuery) returns NULL.
This is the reason why you cant use that loop again, since mysqli has finished fetching the results and the mysqli_fetch_array($newsQuery) now returns NULL untill you make a new query.
Try populating a variable with the results first, then loop on that variable:
$results = array();
while ($row = mysqli_fetch_array($newsQuery)) {
$results[] = $row;
}
foreach ($results as $key => $row) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
foreach ($results as $key => $row) {
echo $row["news_content"];
}
While it is best to avoid logic that results in looping through a result set twice, if necessary you need to reset the result set back to the start:-
mysqli_data_seek($newsQuery, 0);
Because you already fetch the value of $newsQuery Try this code
//temporary save the news content into array
$content = array();
$x=0;
while ($row = mysqli_fetch_array($newsQuery)) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
$content[$x]= $row["news_content"];
$x++;
}
and if you want to retrieve it
//now retrieve it
for($y=0; $y<count($content); $y++)
{
echo $content[$y]+"<br/>";
}
Say for example this is my code:
$query = "SELECT * FROM ...";
$exec_query = mysql_query($query, $db_connect);
$fetchdetails = mysql_fetch_array($exec_query);
I am using an if condition like this:
if ($fetchdetails['field_name'] == 3) {
do something;
}
else {
}
But in this, only 1 row is compared from the fetchdetails array. What can I do to compare each row in that array with 3? I don't want any OOP's solutions, please, I want to stick with traditional coding. Thank you.
You should try this:
while($fetchdetails = mysql_fetch_array($exec_query)) {
if ($fetchdetails['field_name'] == 3) {
do something;
}
else {
}
}
That's because, with the while(...) condition, you'll iterate over all db (selected) records.
The loop will stop in an automatic way as soon as mysql_fetch_array finish record.
I'll remember you that mysql_fetch_array
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. (from manual)
and that will allow "you" to stop iteration process.
If you mean that you want to compare every row of the $fetchdetails array, then
foreach($fetchdetails as $index => $value) {
if($value == 3) {
// do something
}
}
Should do it! If you want to iterate over every SQL value, see the other answer.