Is this the right approach in using unique ID

Hi,

I bind the below ID with javascript, but I’m not sure if it’s the right method to do so?
The PHP:


while($row = $result->fetch_object()) {
     echo "<li>";
     echo "<div id=mp3Item>";
     echo "<div id=mp3Track>";
     echo $row->mp3_id;
     echo "</div>";
     echo "<div id=mp3Title>";
     echo $row->mp3_title;
     echo "</div>";
     echo "<div id=mp3Lenght>";
     echo $row->mp3_duration;
     echo "</div>";
     echo "</div>";
     echo "</li>";
}else{
     echo "<li>";
     echo "<div id=mp3Item>";
     echo "<div id=mp3Track>";
     echo 1;
     echo "</div>";
     echo "<div id=mp3Title>";
     echo "default song";
     echo "</div>";
     echo "<div id=mp3Lenght>";
     echo "04:01";
     echo "</div>";
     echo "</div>";
     echo "</li>";
     .
     .
     .
}

The javascript function plays the mp3 item when click.
Should I rename the id in the else {} and write new javascript function separately, what if my database expanded incrementally?

If you use the code above, each row will have mp3Item and mp3Track (etc) as their IDs for those items, so they won’t be unique. Which means that if you try to target it with JavaScript, you’d only target the first one.

Simple to change though, you can change what you have to classes and then target elements that way, to uniquely identify each row, you could add an id on the list item.

like so:

while($row = $result->fetch_object()) {
     echo '<li id="mp3_'.$row->mp3_id.'">';
     echo '<div class="mp3Item">';
     echo '<div class="mp3Track">';
     echo $row->mp3_id;
     echo '</div>';
     echo '<div class="mp3Title">';
     echo $row->mp3_title;
     echo '</div>';
     echo '<div class="mp3Lenght">';
     echo $row->mp3_duration;
     echo '</div>';
     echo '</div>';
     echo '</li>';
}

Note that “while” does not have an “else” clause, it will simply go through $result->fetch_object() until there are no more rows to be found. If required you could do a separate check to see if there are any results…

(It’s been a while since I’ve done any PHP, but pretty sure ->num_rows is the property you’re after):


if ($result->num_rows == 0) {
     echo '<li id="mp3_default">';
     echo '<div class="mp3Item">';
     echo '<div class="mp3Track">';
     echo 1;
     echo '</div>';
     echo '<div class="mp3Title">';
     echo 'default song';
     echo '</div>';
     echo '<div class="mp3Lenght">';
     echo '04:01';
     echo '</div>';
     echo '</div>';
     echo '</li>';
}

Thanks