Does MySQL cache queries?
This is likely an artifact of the MySQL Query Cache.
You execute the SQL query, MySQL caches its result and the next execution if fast. When you run the script to insert the data in tables referenced by your query, the result cache gets invalidated and the query must be executed "for real" the next time.
From the MySQL documentation linked above:
A query mix consisting almost entirely of a fixed set of SELECT statements is much more likely to benefit from enabling the cache than a mix in which frequent INSERT statements cause continual invalidation of results in the cache.
Yes, mySQL (in common with all other popular database products) caches the queries that are made to it.
The caching is pretty clever -- it can often use a cache for a query even if the exact parameters of the query are not the same. This can make a big difference to performance.
Caching is controlled entirely inside the DB server software; you do not have any visibility of what the cache contains, nor how long a given item remains in the cache; it could be overwritten at any given moment depending on what other queries are being called, etc. It is there to aid performance, but it should not be relied on for performance.
You can read more about it here in the MySQL manual
In addition, using PDO allows you to write your queries as "Prepared statements", binding the parameters rather than hard coding them into a plain text query string. This also has caching implication on the DB server and for queries that are repeated, will also improve performance.