Jump to content

Numbering mysql results from 1-6


nextman

Recommended Posts

hi, i need some help with numbering rows in a mysql table after i select them. ill be brief, im going to run a mysql query that selects the 6 latest articles from my database , id like to assign a number to each of the rows it selects. ie, it pulls 6 rows and the first row is $1, the second row is $2 and the third row is $3 etc. any help would be appreciated :)

Link to comment
Share on other sites

You can use variables in MySQL.

 

Before you run the query, you create a variable named @seq and initialize it to 0.

set @seq = 0;

 

Then you issue the query:

select @seq := @seq + 1 as thecount, login from wv_user;

 

For each row, MySQL will add 1 to the current value of @seq.  It will return this value in the dataset.  It also updates @seq variable to this incremented value, so the next row will increment one further.

 

It's essentially the same as:

 

<?php
$inc = 0;
$items = array( 'a', 'b', 'c', 'd' );
foreach( $items as $item ) {
  echo ($inc = $inc + 1) . ' ' . $item . "\n";
}

Link to comment
Share on other sites

thanks guys, im trying to use the first bit of code you suggested. heres what i got:

 


//	Get latest articles
$sql = "SELECT * FROM art_articles	WHERE status = '1' ORDER BY date DESC LIMIT 6";

$result = mysql_query($sql);


$i = 0;
$res = array();
while($row = mysql_fetch_assoc($result)) 
{
    $res[++$i] = $row;
}

$row1id = $row[1]['id'];
$row2id = $row[2]['id'];
$row3id = $row[3]['id'];
$row4id = $row[4]['id'];
$row5id = $row[5]['id'];
$row6id = $row[6]['id'];

 

but i cant seem to get it to work. is there something wrong with my code?

Link to comment
Share on other sites

im trying to display the 6 articles in dofferent locations on the same page. im trying this now but its not displaying the article ids:

 

	$sql = "SELECT * FROM art_articles WHERE status = '1' ORDER BY date DESC LIMIT 6";

$result = mysql_query($sql);


$i = 0;
$res = array();
while($row = mysql_fetch_assoc($result)) 
{
    $res[++$i] = $row;
}


echo $row[1]['id'];
echo $row[2]['id'];
echo $row[3]['id'];
echo $row[4]['id'];
echo $row[5]['id'];
echo $row[3]['id'];

 

:s

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.