When new emails are added to the database, only the details of one email are inserted into the database

My journey with stackoverflow developers led me to successfully complete my first task, which involved creating an incoming email insert to the database query.

Here is the code I used:

#!/usr/bin/php -q
<?PHP 

/* connect to gmail */
$hostname = '{example.org:995/pop3/ssl/novalidate-cert}'; 
$username = 'user';
$password = 'pass';

/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to SERVER: ' . imap_last_error());


/* grab emails */
$emails = imap_search($inbox,'ALL');

/* if emails are returned, cycle through each... */
if($emails) {

    /* begin output var */
    $output = '';

    /* put the newest emails on top */
    rsort($emails);

    /* for every email... */
    foreach($emails as $email_number) {

        /* get information specific to this email */
        $overview = imap_fetch_overview($inbox,$email_number,0);
        $message = imap_fetchbody($inbox,$email_number,2);

        /* output the email header information */
        //$read_status  = '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
        $subject = $overview[0]->subject;
        $from    = $overview[0]->from;
        $received_date = '<span class="date">on '.$overview[0]->date.'</span>';
        //$output.= '</div>';

        /* output the email body */
        $output= '<div class="body">'.$message.'</div>';
    }

    //echo $output;
$servername = "localhost";
$username = "username ";
$password = "password ";
$dbname = "dbname";

$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());

//INSERT INTO DATABASE

$sql = "INSERT INTO ads(`banner_name`, `hd_image`)VALUES('".$message."', '".$subject."') ";
$result = mysqli_query($conn, $sql);
} 

/* close the connection */
imap_close($inbox);

?>

The code is functioning well, but I am facing a challenge. Every time I send a new email to my address, the query executes and inserts the details of the first email instead of the newly sent email. How can I resolve this issue?

Additionally, I would like to know how to download an attachment if an email is received with one.

I truly appreciate your assistance.

Answer №1

To retrieve the most recent email from an array, you should utilize the asort() function instead of rsort(). This is because rsort() will reverse the order of the array, while asort() will maintain the original order and allow you to access the latest record at the last index.

asort($emails); // Retrieve the latest email from the last index.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to access the data from a json response

I'm dealing with this JSON data: Print_r($send); {"status":"INSUFFICIENT_APIBALANCE"} and I also have: $send = var_dump(json_decode($send)); Now, I'm attempting to check for a specific condition: if ($send->status == "INSUFFICIENT ...

Guide on obtaining JSON data in an android application through a PHP file?

I am a beginner in Android development and I have recently created a simple data fetching application. However, I am facing an issue where I am only able to retrieve the value of one variable from my PHP file, even though both variables are present in the ...

How does Java compare to PHP's list() function when it comes to accessing variables in an array?

How can you achieve a similar functionality to PHP's list() function in Java? Consider the following example: $matches = array('12', 'watt'); list($value, $unit) = $matches; ...

How to Invoke a Class Function Inside a Nested Foreach Loop in PHP

When attempting to interact with functions in the "HelperImageGallery" class from a nested foreach loop, I encounter errors saying "Trying to access array offset on value of type bool." The "HelperImageGallery" class is located in a separate file that has ...

"Error: The ajax call to the dojo endpoint is not retrieving the

Uncertain where I might have made a mistake as the code appears correct to me. I have confirmed that file.php -> mod_rewtite -> file.json is functioning properly by testing the JSON response through jQuery. However, the following code snippet immediately t ...

Symfony ElasticaBundle event listener and method for building queries

I want to upload leads in elastic only when their status is approved. Here is my mapping: persistence: driver: orm model: Artel\ProfileBundle\Entity\Lead provider: query_builder_method: createIsActiveQueryBuilder lis ...

What is the most efficient way to retrieve a model object in Laravel without loading its related model object?

Currently, I am working on a Laravel project. Within my model 'Property,' I have a method called 'PropertyRatings' which looks like this: public function PropertyRatings() { return $this->hasMany('App\Models&bs ...

Disorientation among Python class constituents

Coming from a background in Java and PHP, I am now diving into the world of Python. While this may seem like a simple question, it has left me a bit puzzled. For instance, in PHP: class MyClass { private $myMember; public function __construct($myM ...

Using PHP arrays without the need for quotation marks when specifying key strings

When transferring files to the server, I am encountering issues with using variables like $_GET[mode] without single quotes in 'mode'. Everything works fine locally, but once on the server, I start receiving notices. How can I resolve this issue? ...

gather remarks published by a Facebook Page

Is there a way to retrieve the comments made by a Facebook page, such as this one? The code provided only fetches general information. What format should the URL be to retrieve the comments specifically? $Page_ID = 'https://www.facebook.com/nauhote ...

PHP web service issue

Hey there, I'm facing an issue with my webservice that requires a database handler class when receiving a request. It all works perfectly fine when tested locally, but as soon as I hosted the service on a server, these two lines seem to be causing tro ...

Ways to delete a blank key from a MySQL json field

I need to modify a MySQL table with a json field that contains an empty key. I am looking for a way to remove this empty key from the JSON field. Current data: update t1 set info = REPLACE(info, '"": "",', ''); The ...

Creating Custom Queries with Eloquent ORM: A Beginner's Guide

I'm in the process of developing a sleek API and utilizing eloquent ORM. However, I find myself needing to write my own queries on occasion, especially for more intricate database requests. After conducting some research, I attempted the following ap ...

Issue: Json variable is not defined

Retrieve States Based on Chosen Country I have set up three select boxes for choosing area, state, and country. The issue arises when I try to fetch city and area information as it throws an error stating "undefined variable" in other scripts that were fu ...

Is there a Solution for Dealing with Floating Point Rounding Errors?

I've been working on a PHP system and encountered an issue with rounding. Upon investigating, I discovered that the problem lies within the round function in PHP. For example... Rounding 2047.615 to 2 decimal places results in 2047.62 (as expected) ...

Inconsistencies in the logic of PHP operations

$x = 0; if($x == ++$x) // This condition evaluates to true if($x > $x++) // This condition also evaluates to true However, the same code when run in c gives a false result. Why does this discrepancy occur? ...

Storing the information filled out in the form and utilizing it to navigate to the correct destination URL

With the generous assistance and insightful advice from members of Stack Overflow, I am nearing completion of my quiz project. However, I do have a few lingering questions regarding some final touches needed for the project. Before delving into those quest ...

Modifying the DateTime in doctrine proves to be a challenge

Seeking assistance on how to update the DateTime using Doctrine in my controller. The main objective of this page is to enable users to upload photos to a database, with only one upload allowed per user. Although everything else is functioning properly, ...

SQL/PHP challenge: Trouble updating a record

As a newcomer to PHP, I apologize if my question is basic. I am attempting to update a record using PHP / SQL. Despite researching the error message online, I cannot pinpoint the issue within my code: An error occurred: SQLSTATE[HY093]: Invalid paramet ...

"Make sure to specify Safari input field as an email and mark

I am experiencing an issue with a contact form in my HTML/PHP code. Everything seems to be working fine, but when using the SAFARI browser, the form fails to validate if I try to submit without filling out all input fields. For example, my form includes: ...