Jump to content

[SOLVED] Moving to last record (MySQL)


oceans

Recommended Posts

Dear Friends,

 

I need help on MySQL, please advise me how I can move to last record:

Situation:

Say a table contains columns: (1) Number (2) Data (3) Value

 

I have three entries the table

 

(1) Number1 (2) Data1 (3) 1.0

(1) Number2 (2) Data1 (3) 2.0

(1) Number3 (2) Data1 (3) 3.0

 

I do a normal search:

 

<?PHP

 

$result = mysql_query("SELECT `Number` FROM `table` WHERE `Data` = 'Data1'");

}

while($row = mysql_fetch_array($result))

{

$InputFromDataBase[1]=$row['Number'];

}

?>

The output will be “Number1”, please guide me on how to go to the last record, that is I want the value to be “Number3”, Thanks.

 

Link to comment
Share on other sites

ya what am I asking?

 

OK, can you please teach me, how can I use "foreach statement", i remember using in "ASP ODBC", as I will not know how many record will be in the result table.

 

That is list all onto the screen, my original one will give 1 entry, Thrope's one will give one entry, but how to show all three?

Link to comment
Share on other sites

<?php

  if ($result = mysql_query("SELECT Number FROM `table` WHERE Data = 'Data1' ORDER BY Number DESC")) {
    if (mysql_num_rows($result)) {
      while($row = mysql_fetch_assoc($result)) {
        echo $row['Number'];
      }
    }
  }

?>

Link to comment
Share on other sites

Each time you call mysql_fetch_* the current row is returned, and the internal pointer is moved to the next record. When the last record is fetched mysql_fetch_* returns false.

 

This works well with a while loop because while will keep looping until the contained expression is false.

 

The same result can be done with a for loop, but its more work....

 

<?php

  if ($result = mysql_query("SELECT Number FROM `table` WHERE Data = 'Data1' ORDER BY Number DESC")) {
    if ($total = mysql_num_rows($result)) {
      for ($i = 0;$i <= $total, $i++) {
        $row = mysql_fetch_assoc($result);
        echo $row['Number'];
      }
    }
  }

?>

 

A foreach on the other hand is used to loop through arrays, and sometimes objects.

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.