What is the best practice for creating a link with an ID in PHP when inserting data into a database?

When inserting data into a database in PHP and creating a link with an ID, it is best practice to generate a unique ID for the link before inserting the data. This can be achieved by using functions like uniqid() or md5(uniqid()). By generating a unique ID beforehand, you can ensure that each link is distinct and easily identifiable in the database.

// Generate a unique ID for the link
$link_id = md5(uniqid());

// Insert data into the database with the generated link ID
$query = "INSERT INTO links (link_id, url) VALUES ('$link_id', '$url')";
$result = mysqli_query($connection, $query);

if ($result) {
    echo "Link inserted successfully with ID: $link_id";
} else {
    echo "Error inserting link";
}