how to avoid inserting duplicate row in php while update user profile
When users update their profile information, it is important to ensure that certain fields, such as mobile numbers, remain unique across all user accounts. This article explains how to prevent users from updating their profile with a mobile number that is already assigned to another account.
Scenario
Assume you have a table named ls_users with the following columns:
emailphone
When a user updates their profile, you need to:
- Identify the current user using their email address.
- Check whether the new mobile number already exists for another user.
- Allow the update only if the number is not being used by anyone else.
Example Implementation
The following example checks whether the mobile number already exists for another user before performing the update.
<?php
$email = "example@gmail.com";
$newPhone = "1234567890";
$query = mysql_query("
SELECT phone
FROM ls_users
WHERE email NOT IN ('$email')
AND phone = '$newPhone'
");
if (mysql_num_rows($query) > 0) {
echo "This mobile number is already registered. Please use another number.";
} else {
mysql_query("
UPDATE ls_users
SET phone = '$newPhone'
WHERE email = '$email'
");
echo "Profile updated successfully.";
}
?>
How It Works
- The
SELECTquery checks whether the new mobile number already exists for any user other than the currently logged-in user. - If a matching record is found, the update is blocked and an error message is displayed.
- If no matching record exists, the user’s profile is updated with the new mobile number.
Recommended Modern Approach (MySQLi)
The mysql_* functions used in the example above are deprecated and removed in newer PHP versions. For modern applications, use MySQLi or PDO with prepared statements.
Example using MySQLi:
$stmt = $conn->prepare("
SELECT id
FROM ls_users
WHERE email != ?
AND phone = ?
");
$stmt->bind_param("ss", $email, $newPhone);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "This mobile number is already registered.";
} else {
$update = $conn->prepare("
UPDATE ls_users
SET phone = ?
WHERE email = ?
");
$update->bind_param("ss", $newPhone, $email);
$update->execute();
echo "Profile updated successfully.";
}
Best Practice
For maximum data integrity, create a unique index on the phone column:
ALTER TABLE ls_users
ADD UNIQUE (phone);
This ensures that duplicate mobile numbers cannot be inserted or updated, even if validation is missed at the application level.
Conclusion
Validating mobile numbers before updating user profiles helps maintain data consistency and prevents duplicate records. While application-level checks are useful, enforcing uniqueness at the database level with a unique constraint provides the most reliable protection against duplicate entries.
