Core PHP

A Simple MySQL Query

The program below demonstrates how to make a simple MySQL query.

SimpleMySqlQuery.php

<?php
  $sServername = "127.0.0.1";
  $sUsername = "root";
  $sPassword = "MyPassword";
  $sDatabase = "school";

  try {
    // Create the connection object
    $qConnection = mysqli_connect($sServername, $sUsername, $sPassword, $sDatabase);

    // Check that the connection is valid.
    if ($qConnection->connect_error) {
      die("Connection failed: " . $qConnection->connect_error);
    }

    $qSqlCommand = "SELECT event, year FROM historic_events";
    $qResult = $qConnection->query($qSqlCommand);

    if ($qResult->num_rows > 0) {
      // Output data for each row
      while($qRow = $qResult->fetch_assoc()) {
        echo "event: " . $qRow['event']. " - year: " . $qRow['year']. "<br />";
      }
    } else {
      echo "0 results";
    }

    $qConnection->close();
    } catch(Exception $eException) {
      echo "error: " . $eException->getCode() . " " . $eException->getMessage();
    }
?>
 

Output

event: Christopher Columbus discovers America - year: AD 1492
event: The Fall of Rome - year: AD 476
event: The Fall of Constantinople - year: AD 1453
event: The Start of the Black Death - year: AD 1347
event: The End of the Black Death - year: AD 1351
event: The Founding of Rome - year: 753 BC
event: The Founding of the Roman Republic - year: 509 BC
event: The Establishment of the Roman Empire - year: 27 BC
event: The East-West Schism - year: AD 1054
event: The Start of the Great Schism - year: AD 1378
event: The End of the Great Schism - year: AD 1417
event: The Birth of Jesus Christ - year: AD 1
event: The Death and Resurrection of Jesus Christ - year: AD 33
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.