An example PHP MySQL script (with a SQL 'SELECT' query)

As a quick note to self, here is some source code for a simple example PHP script that runs a SQL SELECT query against a MySQL database:

#!/Applications/MAMP/bin/php/php5.6.10/bin/php

<?php
  $servername = "localhost";
  $username = "d8_user";
  $password = "d8_pass";
  $dbname = "aa_d8";

  # connect to the database
  $conn = new mysqli($servername, $username, $password, $dbname);
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }

  # execute a query and output its results
  $sql = "SELECT * FROM node__field_photo";
  $result = $conn->query($sql);
  if ($result->num_rows > 0) {
      // output data of each row
      while($row = $result->fetch_assoc()) {
          echo "bundle: " . $row["bundle"]. ", " . $row["entity_id"]. ", " . $row["field_photo_target_id"]. "\n";
      }
  } else {
      echo "0 results";
  }

  $conn->close();
 
?>

Sorry, I’m not going to offer any explanation about that, other than to say that the SELECT query is intended to run against a Drupal database table. Other than that, I assume that you know PHP and MySQL, and just need a little starter script to get going. This script works as of PHP 5.6.* running under MAMP on May 6, 2016, and it’s based on the script at the URL I’ve linked to.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.