What are the best practices for checking if a name already exists in a database when adding new data in PHP?
When adding new data to a database in PHP, it is important to check if a name already exists to avoid duplicates. One common practice is to query the database to see if the name already exists before inserting the new data. This can be done using a SELECT query with a WHERE clause to search for the name in the database. If a record is returned, then the name already exists and the new data should not be added.
// Assuming $conn is the database connection object
$name = "John Doe"; // Name to check if it already exists
// Query to check if the name already exists in the database
$query = "SELECT * FROM table_name WHERE name = '$name'";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0) {
echo "Name already exists in the database.";
} else {
// Proceed with inserting the new data into the database
}