Jump to content

Looping Query


CanMan2004

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
Link to comment
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.
Link to comment
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]
Link to comment
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 ;)
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.