title: Why is my query slow in PHP and fast in PHPMYadmin?
body: <p>The following query is optimized with indexes. The time is measured exactly before and after the query execution within PHP and takes sometimes 10 or 20 seconds. I does not seem to depend on the number of rows as sometimes the number of rows is less than 10 and even then the query runs slow. Apart from the query execution as shown below PHP does not do any other operations.</p>
  
  <pre><code>SELECT * FROM (
    SELECT o.op AS orid,
    (3959 * acos(cos(radians(59.4369583424862))
    * cos(radians(d.latitude)) * cos( radians( d.longitude) -
    radians(24.7535276412964)) + sin(radians(59.4369583424862))
    * sin( radians( d.latitude ) ) ) ) AS distance
    FROM (
    SELECT * FROM d WHERE
      d.type='rdw' AND d.longitude &gt; 24.4837311595 AND
      d.longitude &lt; 25.0233241231 AND d.latitude &gt; 59.1671618607 AND
      d.latitude &lt; 59.7067548243
    ) AS d
    LEFT JOIN o ON d.destinid = o.destinid
    LEFT JOIN op ON o.operatorid = op.operatorid
    having distance &lt; 30
    ORDER BY distance
  ) AS t
  GROUP BY trajectoperatorid
  LIMIT 0, 30
  </code></pre>
  
  <p>This is how the query is executed:</p>
  
  <pre><code>$stmt = $pdo-&gt;prepare($sql1);
  $stmt-&gt;execute();
  $rows = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC); //foreach($rows as $row){
  </code></pre>
  
  <p>A connection to the datase already existed before first time measurement.</p>
  
  <p>When running the same query in phpmyadmin using the SQL_NO_CACHE it takes consistently just 0.06 seconds. Why is exactly the same query slow when it is running within the PHP script?</p>
  
  <p>Below is the php scrip:</p>
  
  <pre><code>write_log_file('Start query'.date('l jS \of F Y h:i:s') . substr((string)microtime(), 1, 8));
  
  $sql1 = "
  SELECT * FROM (
    SELECT o.op AS orid,
    (3959 * acos(cos(radians(59.4369583424862))
    * cos(radians(d.latitude)) * cos( radians( d.longitude) -
    radians(24.7535276412964)) + sin(radians(59.4369583424862))
    * sin( radians( d.latitude ) ) ) ) AS distance
    FROM (
    SELECT * FROM d WHERE
      d.type='rdw' AND d.longitude &gt; 24.4837311595 AND
      d.longitude &lt; 25.0233241231 AND d.latitude &gt; 59.1671618607 AND
      d.latitude &lt; 59.7067548243
    ) AS d
    LEFT JOIN o ON d.destinid = o.destinid
    LEFT JOIN op ON o.operatorid = op.operatorid
    having distance &lt; 30
    ORDER BY distance
  ) AS t
  GROUP BY trajectoperatorid
  LIMIT 0, 30";
  
  $stmt = $pdo-&gt;prepare($sql1);
  $stmt-&gt;execute();
  $rows = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC);
  </code></pre>