Cursussen/Courses Codesnippets     Top 
B4A-JSON - PHP scripts


1. Database config
To use the MySQL database in PHP we have to write a few scripts.
You can save these scripts in a folder 'translations' from the www root folder from the local web server.
A first script contains the database configuration settings that will be used in the database class.
Of course you have to change the DB_USER, DB_PASSWORD and DB_DATABASE constants when you use an online database server.
Here is the code:
<?php
// dbconfig.php
define('DB_USER', "root");
define('DB_PASSWORD', "root");
define('DB_DATABASE', "translations");
define('DB_SERVER', "localhost");
define('DEBUGFLAG', "true");
?>


2. Database class.
In the database class you can use the constructor to set up a connection to the Mysql database.
The class definiton:
<?php
// database.php
require "dbconfig.php";
class database {
	private $conn;
The constructor:
	function __construct($host = DB_SERVER, $dbname = DB_DATABASE, 
						 $user = DB_USER, $password = DB_PASSWORD) {
		try {
			$conn = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $password);
			$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$this->conn = $conn;
		}
		catch(PDOException $e)
		{
			if (DEBUGFLAG === "true") {
				echo "<div><b>Error: " . $e->getmessage() . "</b></div><br>\n";
			} else {
				echo "<div><b>Error: database error (1).</b></div><br>\n";
			}
			return -1;
		}	
	}
This code will allow you to declare a database object variable. In the next section you will find an example.
The execute_query method:
	public function execute_query($sql,$table,$rstype = "") {
		try {
			$result = $this->conn->query($sql);
			if (is_numeric($result) and ($result < 0)) return -1;
			$response = array();
			$fields_array = $this->get_fields($table);
			$response[] = $fields_array;
			foreach($result->fetchAll(PDO::FETCH_NUM) as $rec) {
				$response[] = $rec;
			}
			if ($rstype == "json") {
				return json_encode($response);	// string containing JSON object
			} else {
				return $response;		// array to add to another array
			}	
		}
		catch(PDOException $e)
		{
			if (DEBUGFLAG === "true") {
				echo "<div><b>Error: " . $e->getmessage() . "</b></div><br>\n";
			} else {
				echo "<div><b>Error: database error (2).</b></div><br>\n";
			}
			return -1;			
		}
	}
The result type argument of this execute_query method allows you to choose a return type: a string containing a JSON object or an array that can be added to another array which then can be encoded as a string containing a JSON object. You will see an example in the next section.
The get_fields method:
	private function get_fields($table) {
		$sql = "SELECT column_name,data_type FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table AND TABLE_SCHEMA = :schema";
		$result = $this->conn->prepare($sql);
		$result->execute(array(':table' => $table,':schema' => DB_DATABASE));
		$fields = array();
		while($row = $result->fetch(PDO::FETCH_ASSOC)){
			$fields[] = $row["column_name"];                
		}
		return $fields;
	}
}	// end of the class


3. JSON arrays
In the lists_JSON.php file you can place a test to prevent the script from giving a list when the required key variable doesn't contain the key value.
This script requires the database.php script. The constructor from the database class is executed with the keyword 'new' and a $db object variable for the database is created.
With this object variable you can call the execute_query method. The result set will be an array that can be added to the $json_array that will be encoded as a string containing a JSON object.
<?php
// lists_JSON.php
if (isset($_POST["B53bLkN2ekAUHRFddzuJ"]) and ($_POST["B53bLkN2ekAUHRFddzuJ"] == "Ud4wvW4DM74VPhNsUz3y")) {
	require("database.php");
	if (!isset($db)) $db = new database();
	$json_array = array(); 
	$sql = "SELECT * FROM category order by name";
	$rscat = $db->execute_query($sql,"category");
	$json_array[] = $rscat;		// index 0
 	$sql = "SELECT * FROM subcategory order by name";
	$rssubcat = $db->execute_query($sql,"subcategory");
	$json_array[] = $rssubcat;	// index 1
	$sql = "SELECT * FROM item order by name";
	$rsitem = $db->execute_query($sql,"item");
	$json_array[] = $rsitem;		// index 2
	echo json_encode($json_array);
}
?>
The resulting JSON object will have this structure: