Created
June 15, 2022 05:26
-
-
Save joshirohit100/71292f5355a7a4645552c5c6b6a10640 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$servername = 'localhost'; | |
$username = 'drupal'; | |
$password = 'drupal'; | |
$database = 'drupal'; | |
$table_name = 'employees'; | |
try { | |
$conn = new \PDO("mysql:host=$servername;dbname=$database", $username, $password); | |
// set the PDO error mode to exception | |
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$query = $conn->query('select emp_email, emp_name from ' . $table_name); | |
// Returns all rows with key based on first column i.e. emp_email | |
// We are assuming uniqueness based on the email address only. | |
// This means two employess can have same name but not same | |
// email address and thus bitwise '|PDO::FETCH_GROUP' to group | |
// the result based on email. | |
$results = $query->fetchAll(PDO::FETCH_COLUMN | PDO::FETCH_GROUP); | |
foreach ($results as $mail => $names) { | |
// If names are more than 1, this means this email has duplicate records. | |
// Delete the rows | |
if (count($names) > 1) { | |
// Delete all records based on email. | |
$statement = $conn->prepare("DELETE FROM $table_name WHERE emp_email=?"); | |
$statement->execute([$mail]); | |
// Insert the record. | |
$statement = $conn->prepare("INSERT INTO $table_name VALUES('$names[0]', '$mail')"); | |
$statement->execute(); | |
} | |
} | |
// Close the connection. | |
$conn = null; | |
} catch (\PDOException $e) { | |
echo "Connection failed: " . $e->getMessage(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment