So i am trying to store emails from gmail, i have already connected everything and i manage to store all the email content into database but now i have problem that every time that i refresh page the same emails are being stored in database.
$bodyText = imap_fetchbody($inbox,$email_number,1.2);
if(!strlen($bodyText)>0){
$bodyText = imap_fetchbody($inbox,$email_number,1);
}
$subject = imap_headerinfo($inbox,$email_number);
$subject = $subject->subject;
$stripped = str_replace('*', '<br>', $bodyText);
$sql = "SELECT id, subject, body FROM emails";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$email_subject = $row['subject'];
if ($subject == $email_subject) {
echo "Email already in database";
}else{
$sql = "INSERT INTO emails (subject, body)
VALUES ('".$subject."', '".$stripped."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
} else {
echo "0 results";
}
So i tried using this
if ($subject == $email_subject) {
echo "Email already in database";
}else{
$sql = "INSERT INTO emails (subject, body)
VALUES ('".$subject."', '".$stripped."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Which is suposed to check if in the database there is emails with the same subject, and if there is it will display "Email already in database" and if there isn't its suposed to display "New record created successfully"
Put something is wrong and i keep getting same emails in the database, so each time that i reffresh whole inbox of my email goes into database
First of all, you should always use prepared statements of PDO or MySQLi to prevent SQL Injections.
Also looks like you are looping your entries in the database and checking your current email against every entry. What you should do is to use SELECT query with subject of current email as a WHERE parameter to check if this subject is already in the database.
Alternatively use ON DUPLICATE KEY UPDATE
when inserting new record.