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