开发者

HOw do I limit array to a certain number?

开发者 https://www.devze.com 2023-01-02 20:39 出处:网络
actually what I am trying to do is store incoming searches in a database and then display to a web page limiting to a certain number say 10 with the heading of \"Recent Searches\". if you LIMIT 10 in

actually what I am trying to do is store incoming searches in a database and then display to a web page limiting to a certain number say 10 with the heading of "Recent Searches". if you LIMIT 10 in database query then It stops after 10. so thought will cut off loop but both c开发者_Go百科ase it stops at 10. so after that what ever searches happens it wont update it. is there any one can help me in this situation??

$result = mysql_query("SELECT * FROM query ORDER BY regtime DESC");
while($row = mysql_fetch_array($result))
{
  echo "<img src='bullet.gif' align='absmiddle' class='col1ab'><a class='col1ab' href=".$row['web']." >www.".$row['web']."</a><br>";
}


$count = 0;
$result = mysql_query("SELECT * FROM query ORDER BY regtime DESC");
while($count < 10 && $row = mysql_fetch_array($result))
{
  $count++;
  echo "<img src='bullet.gif' align='absmiddle' class='col1ab'><a class='col1ab' href=".$row['web']." >www.".$row['web']."</a><br>";
}


Limit what array? I don't see an array in your code. If you want to limit the number of echos you make, you can count a variable and then break once you reach 10, like so:

$result = mysql_query("SELECT * FROM query ORDER BY regtime DESC");
while($row = mysql_fetch_array($result))
{
  if ($i++ >= 10) break;
  echo "<img src='bullet.gif' align='absmiddle' class='col1ab'><a class='col1ab' href=".$row['web']." >www.".$row['web']."</a><br>";
}


Not the requested answer but ...

Don't store searches. Make your data efficiently searchable.(search friendly schema,index, partitioning, more hardware)

reasons: query data is no longer real time if read from query table more space is needed for duplicate data in query table more io is required to fill the query table

use 2 queries or estimate (how critical is accuracy?(since it is stored, the number is most likely not accurate))

"SELECT * FROM query ORDER BY regtime DESC" with LIMIT(10) "SELECT count(*) FROM query..."


Try this:

$result = mysql_query("SELECT * FROM query ORDER BY regtime DESC");

$counter = 0;
while($row = mysql_fetch_array($result))
{
  echo "<img src='bullet.gif' align='absmiddle' class='col1ab'><a class='col1ab' href=".$row['web']." >www.".$row['web']."</a><br>";

  if (++$counter === 10) break;
}

The loop increments the value of $counter variable and when it becomes 10, the break keyword exits out of the while loop there by giving you just 10 iterations.


Why did no one come up with:

SELECT * FROM query ORDER BY regtime DESC LIMIT 0,6

0

精彩评论

暂无评论...
验证码 换一张
取 消