What is the best practice for creating unique IDs for each record in a MySQL database when displaying a list of records in PHP?
When displaying a list of records in PHP from a MySQL database, it is best practice to use a unique identifier for each record to ensure that each record is distinguishable. One common approach is to use the auto-increment primary key field in the database table as the unique identifier.
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Query database for records
$sql = "SELECT * FROM records";
$result = $conn->query($sql);
// Display list of records with unique IDs
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div id='record_" . $row["id"] . "'>" . $row["name"] . "</div>";
}
} else {
echo "0 results";
}
// Close database connection
$conn->close();