Jump to content


How do I select a single row? and another question...


  • Please log in to reply
4 replies to this topic

#1 Guest_kilbad_*

Guest_kilbad_*
  • Guests

Posted 08 August 2006 - 04:32 PM

Two questions:: First, how would I modify the code below to merely select a single row from the database?  Let's say row two?  I know it can probably be done by changing the query but I do not know what the syntax would be..

$query="SELECT * FROM contactbook";
$result=mysql_query($query);

$num=mysql_numrows($result);

$i=0;
while ($i < $num) {
$id=mysql_result($result,$i,"id");
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");

echo "$id $first $last";

$i++;
}

Second, and unrelated to the above code, how do I output rows of data from the database, let's say based off a column of first names, in alphabetical order?


Thank you so much in advance!

Brendan

#2 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 08 August 2006 - 04:39 PM

If you want to select row 2 use this as the query:
$query="SELECT * FROM contactbook WHERE id='2'";
That will work if the id fields is an auto incremented row.

For you secound question use and order by clause opn the end of your query like so:
SELECT * FROM tbl_name ORDER by col_name ASC

If you want to learn more about SQL Queries have a read through the SQL Tutorials over at w3schools.com and possibly read through the tutorials over at php-mysql-tutorial.com/


#3 Orio

Orio
  • Staff Alumni
  • Advanced Member
  • 2,491 posts

Posted 08 August 2006 - 04:56 PM

I just have a comment about the first question. In most of the cases, the query that wildteen88 suggested will work fine, but if the row "WHERE id='2'" was deleted in some point, nothing will be selected. So I think a better query to select the second row is:
"SELECT * FROM `contactbook` ORDER BY id ASC LIMIT 2,1"

Orio.
Think you're smarty?

(Gone until 20 to November)

#4 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 08 August 2006 - 05:15 PM

good point there Orio.

#5 Guest_kilbad_*

Guest_kilbad_*
  • Guests

Posted 08 August 2006 - 11:33 PM

thank you both so much!  this has been very helpful!






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users