Ajax Made Simple Part 11: MySQL/SQLite on the server

PHP has built in support for MySQL and SQLite. If you have a database on your server, it’s easy to query it and return the result to your app. Here’s a very simple example of accessing MySQL:


$host = "localhost";
$databasename = "myDatabaseName";
$username ="myUsername";
$password = "myPassword";

$con = mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = file_get_contents("php://input"); 
$results = mysql_query($query);

if (mysql_errno()) { 
  header("HTTP/1.1 500 Internal Server Error");
  echo $query.'n';
  echo mysql_error(); 
  $rows = array();
  while($r = mysql_fetch_assoc($results)) {
    $rows[] = $r;
  echo json_encode($rows);

You’ll want to address security with this. There is no parsing of the incoming query string, so someone could conceivably put some malicious code in there and you may want to determine that the person requesting the info is authorized to do so.