Jump to content

Archived

This topic is now archived and is closed to further replies.

CanMan2004

Looping Query

Recommended Posts

Hi all

I have a php query which checks a database for a particular number, for example

23

if the query does no find a result, I have a 2nd query which checks for the next number, for example

24

I want to loop the query, so that it keeps returning results with the number above the one just queried.

So it would do the query for

23

then loop to do

24

then loop to do

25

and so on.

The query I use is

[code]<?
$sql = "SELECT * FROM data WHERE `number` LIKE '%".$number."%'";
$show = @mysql_query($sql,$connection) or die(mysql_error());
$num = mysql_num_rows($show);

while ($rows = mysql_fetch_array($show)) {
?>[/code]

Is this an easy function to add?

Any help would be great.

Thanks in advance

Dave

Share this post


Link to post
Share on other sites
[code]<?php

//$number is the number used in the query

$rows=0;

while($rows==0)
{
$sql = "SELECT * FROM data WHERE `number` = '$number'";
$result = mysql_query($sql);
$rows = mysql_num_rows($result);
if($rows==0)
  {
   $number++;
  }
}

echo "Result found for $number";
while ($row = mysql_fetch_array($show)) {
//rest of code

?>[/code]

Orio.

Share this post


Link to post
Share on other sites
slightly different approach:
[code]
<?php
$sql = -1;
// set $i to your minimum and $i <= MAXIMUM
for ($i = 23; $i <= 26; $i++) {
  $sql = mysql_query("SELECT * FROM data WHERE `number` = '$id'");
  if (mysql_num_rows($sql) > 0) break;
}

// use $sql to display your results
?>
[/code]

Share this post


Link to post
Share on other sites
if you know your min and max, just do this, without a loop:

[code]
<?php
  $min = 1; // or whatever
  $max = 10; // or whatever
  $sql = "select * from data where number between '$min' and '$max'";
  $result = mysql_query($sql);
?>
[/code]

Share this post


Link to post
Share on other sites
[quote author=Crayon Violent link=topic=108508.msg436601#msg436601 date=1158596452]
if you know your min and max, just do this, without a loop:
[/quote]

actually, based on his first post, he only wants to continue the loop if [b]Nothing[/b] is returned from the existing query... hence the loops ;)

Share this post


Link to post
Share on other sites
hmmm....

yeah i suppose i see what you're saying.  if he wants the data from row one, but nothing is found, then he wants the data from row 2, but if nothing is found, then get the value from row 3, etc.. okay i'll buy that.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.