Jump to content

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


Guest kilbad

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
Link to comment
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]
Link to comment
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.
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.