Jump to content

Archived

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

Guest kilbad

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

Recommended Posts

Guest kilbad
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..

[code]
$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++;
}
[/code]

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

Share this post


Link to post
Share on other sites
If you want to select row 2 use this as the query:
[code]$query="SELECT * FROM contactbook WHERE id='2'";[/code]
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:
[code]SELECT * FROM tbl_name ORDER by col_name ASC[/code]

If you want to learn more about SQL Queries have a read through the SQL Tutorials over at [url=http://www.w3schools.com/sql/sql_intro.asp]w3schools.com[/url] and possibly read through the tutorials over at [url=http://www.php-mysql-tutorial.com/]php-mysql-tutorial.com/[/url]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest kilbad
thank you both so much!  this has been very helpful!

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.