Jump to content

[SOLVED] Position of result within MySQL fetched array


gray8110

Recommended Posts

I'm using a query from a MySQL table to generate the code for a pulldown menu. Within that menu, each item has a nested UL that I'd like to assign a unique class to (so I can use CSS to position it.) I envision giving the UL a class name that is concatenated to the index position of the result in the array fetched from the query. I thought the variable below would work, but it returns 0 for the index of every result.

 

<?php

$position = key($row);
echo "<ul class='nl" . $position . "></ul>";

?>

 

The query is pulling the 12 most recent entries from the table (and there are more than 12 entries) so I can't use the index). I need each result to assign a unique class to the UL, but the class needs to be constant based on the position of the result. How can I accomplish this?

 

Here's the code as is. Thanks

 

<?php
$result = mysql_query("SELECT * FROM sv_newsbrief ORDER BY ID DESC LIMIT 12", $connection);

if (!result) {
die("Database query failed: " . mysql_error());
}

while ($row = mysql_fetch_array($result)) {

$filename = $row["filename"];
$issue = $row["issue"];
$item1 = $row["item1"];
$item2 = $row["item2"];
$item3 = $row["item3"];


echo 
    "<li><a target='_blank' href='../images/Newsletters/PDF/" . $filename . "'>" . $issue . "</a>
        <ul class='subNews'>
		<li class='preview'>In This Issue:</li>
            <li>" . $item1 . "</li>
            <li>" . $item2 . "</li>";
if ($item3 == "") {
}

else {
     echo  "<li>" . $item3 . "</li>";
}
echo   		
	"</ul>
</li>";

}

?>

Before your while loop, declare a variable $position = 0. Then, at the end of each while loop, increment the $position variable by one. Then you can use the $position variable inside your while loop wherever you need it to.

 

Here's the code:

<?php
$result = mysql_query("SELECT * FROM sv_newsbrief ORDER BY ID DESC LIMIT 12", $connection);

if (!result) {
   die("Database query failed: " . mysql_error());
}

$position = 0; // this was added

while ($row = mysql_fetch_array($result)) {

$filename = $row["filename"];
$issue = $row["issue"];
$item1 = $row["item1"];
$item2 = $row["item2"];
$item3 = $row["item3"];


echo 
    "<li><a target='_blank' href='../images/Newsletters/PDF/" . $filename . "'>" . $issue . "</a>
        <ul class='subNews'>
         <li class='preview'>In This Issue:</li>
            <li>" . $item1 . "</li>
            <li>" . $item2 . "</li>";
if ($item3 == "") {
}

else {
     echo  "<li>" . $item3 . "</li>";
}
echo         
      "</ul>
   </li>";
   
    $position++; // increment the position
}

?>

Archived

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

×
×
  • 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.