PHP e MYSQL
Questa lista di libri è caricata dinamicamente dal database con AJAX!
Questa lista di libri è caricata dinamicamente dal database con AJAX!
E' ora di usare le potenzialità di PHP per creare al volo documenti XML e JSON lato server, che poi possano essere parsati lato client da Javascript
Ecco un esempio funzionante per creare una lista di libri
mysql_1.html
//function called when user press the button
<button onclick='process()'>Carica lista</button>
<!-- wrapper of server response -->
<div id="myDivElement"></div>
mysql_1.js
// JavaScript Document
// contiene il riferimento all'oggetto XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// ritrova l'oggetto XMLHttpRequest
function createXmlHttpRequestObject() {
// contiene il riferimento all'oggetto XMLHttpRequest
var xmlHttp;
// se il browser è Internet Explorer 6 o più vecchio
if(window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
}
// se è Mozilla o altri
else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
// ritorna l'oggetto o errore
if (!xmlHttp) {
alert("Error creating the XMLHttpRequest object.");
} else {
return xmlHttp;
}
}
function process() {
// se esiste l'oggetto
if (xmlHttp) {
// cerca di connetterti al server
try {
// chiamo il file php
xmlHttp.open("GET", "books.php", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
// messaggio di errore
catch (e) {
alert("Can't connect to server:\n" + e.toString());
}
}
// funzione chiamata al variare di onreadystatechange
function handleRequestStateChange() {
// quando readyState è 4, la risposta è completata
if (xmlHttp.readyState == 4) {
// controllo che lo stato della richiesta sia OK
if (xmlHttp.status == 200) {
try {
// fai qualcosa con la risposta del server
handleServerResponse();
} catch(e) {
// mostra un messaggio di errore
alert("Error reading the response: " + e.toString());
}
} else {
// mostra un messaggio di stato
alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
}
}
}
function handleServerResponse() {
// leggo la risposta dal server
var xmlResponse = xmlHttp.responseXML;
// intercetto eventuali errori di Explorer ed Opera
if (!xmlResponse || !xmlResponse.documentElement)
throw("Invalid XML structure:\n" + xmlHttp.responseText);
// intercetto eventuali errori per Firefox
var rootNodeName = xmlResponse.documentElement.nodeName;
if (rootNodeName == "parsererror")
throw("Invalid XML structure");
// ottengo l'XML Document element
xmlRoot = xmlResponse.documentElement;
// ottengo l'array dei titoli ed isbn
titleArray = xmlRoot.getElementsByTagName("title");
isbnArray = xmlRoot.getElementsByTagName("isbn");
// genero l'HTML
var html = "";
// itero nell'array e creo la struttura dell'HTML
for (var i=0; i<titleArray.length; i++)
html += titleArray.item(i).firstChild.data + ", "
+ isbnArray.item(i).firstChild.data + "<br/>";
// ottengo un riferimento al contenitore sulla pagina
myDiv = document.getElementById("myDivElement");
// inserisco l'HTML
myDiv.innerHTML = html;
}
books.php
<?php
// setto il tipo di output come XML
header('Content-Type: text/xml');
// creo l'oggetto DOM (Document Object Model)
$dom = new DOMDocument();
// creo il nodo root
$response = $dom->createElement('response');
$dom->appendChild($response);
// creo l'elemento books e lo inserisco come figlio di response
<response>
$books = $dom->createElement('books');
$response->appendChild($books);
// creo il titolo
$title = $dom->createElement('title');
$titleText = $dom->createTextNode('AJAX, 2nd Ed');
$title->appendChild($titleText);
// creo l'ISBN
$isbn = $dom->createElement('isbn');
$isbnText = $dom->createTextNode('978-1904817726');
$isbn->appendChild($isbnText);
// creo il libro
$book = $dom->createElement('book');
$book->appendChild($title);
$book->appendChild($isbn);
// inserisco il libro
$books->appendChild($book);
// costruisco la stringa XML
$xmlString = $dom->saveXML();
// restituisco la stringa
echo $xmlString;
?>
E se invece come formato di interscambio dati volessi usare JSON? Ecco un esempio
{"books":
[
{"title":"AJAX 1 , 2nd Ed","isbn":"978-1904817724"},
{"title":"AJAX 2, 2nd Ed","isbn":"978-1904817720"},
{"title":"AJAX 3, 2nd Ed","isbn":"978-1904817725"}
]
}
mysql_2.html
<body onload="process()">
<p>The AJAX books of 2011 are:</p>
<div id="myDivElement" />
</body>
mysql_2.js
// JavaScript Document
// contiene il riferimento all'oggetto XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// ritrova l'oggetto XMLHttpRequest
function createXmlHttpRequestObject() {
// contiene il riferimento all'oggetto XMLHttpRequest
var xmlHttp;
// se il browser è Internet Explorer 6 o più vecchio
if(window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
}
// se è Mozilla o altri
else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
// ritorna l'oggetto o errore
if (!xmlHttp) {
alert("Error creating the XMLHttpRequest object.");
} else {
return xmlHttp;
}
}
function process() {
// se esiste l'oggetto
if (xmlHttp) {
// cerca di connetterti al server
try {
// chiamo il file php
xmlHttp.open("GET", "books_json.php", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
// messaggio di errore
catch (e) {
alert("Can't connect to server:\n" + e.toString());
}
}
// funzione chiamata al variare di onreadystatechange
function handleRequestStateChange() {
// quando readyState è 4, la risposta è completata
if (xmlHttp.readyState == 4) {
// controllo che lo stato della richiesta sia OK
if (xmlHttp.status == 200) {
try {
// fai qualcosa con la risposta del server
handleServerResponse();
} catch(e) {
// mostra un messaggio di errore
alert("Error reading the response: " + e.toString());
}
} else {
// mostra un messaggio di stato
alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
}
}
}
// gestisce la risposta del server
function handleServerResponse() {
// leggo la risposta con una libreria
responseJSON = JSON.parse(xmlHttp.responseText);
// genero HTML output
var html = "";
// itero nell'array e creo HTML
for (var i=0; i<responseJSON.books.length; i++)
html += responseJSON.books[i].title +
", " + responseJSON.books[i].isbn + "<br/>";
// ottengo una refernce al contenitore
myDiv = document.getElementById("myDivElement");
// inserisco l'HTML
myDiv.innerHTML = "<p>Server says: </p>" + html;
}
La libreria per il parsing JSON si trova al seguente indirizzo http://www.json.org/json2.js
books_json.php
<?php
// setto l'output a JSON
header('Content-Type: text/json');
// creo l'array di risposta
$response = array(
'books' => array(
array('title' => 'AJAX 1','isbn' =>'978-1904817724'),
array('title' => 'AJAX 2','isbn' =>'978-1904817725'),
array('title' => 'AJAX 3, 2nd Ed','isbn' =>'978-1904817720')
)
);
// encodo l'array in JSON
echo json_encode($response);
?>
Il passo finale è usare un Relational Database Management System (RDBMS) come store dei dati invece di scriverli direttamente nel PHP.
Quindi è necessario:
Nel creare delle tabelle all'interno di un database bisogna conoscere il significato di questi termini:
Un esempio di SQL per creare una tabella:
CREATE TABLE books
(
book_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
book_title VARCHAR(32) NOT NULL,
PRIMARY KEY (book_id)
);
Un esempio di SELECT
SELECT <column list> FROM <table name(s)> [WHERE <restrictive condition(s)>]
Un esempio diINSERT
INSERT INTO <table name> [(column list)] VALUES (column values)
Un esempio di UPDATE
UPDATE <table name> SET <column name> = <new value> [, <column name> = <new value> ... ] [WHERE <restrictive condition>]
Ed uno di DELETE
DELETE FROM <table name> [WHERE <restrictive condition>]
Adesso inseriamo un po' di records nel nostro database:
INSERT INTO books (book_title) VALUES ('Ajax first book');
INSERT INTO books (book_title) VALUES ('Ajax second book');
INSERT INTO books (book_title) VALUES ('Ajax third book');
Adesso è tutto pronto, ecco il codice della nostra demo iniziale:
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Ajax course 2011</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="webmasterneo" />
<meta name="description" content="A short description of your
site here." />
<link rel="stylesheet" href="../../css/style.css" type="text/css" />
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript" src="mysql_3.js"></script>
</head>
<body onload="process()">
<div id="body">
<div class="content">
<h2>PHP e MYSQL</h2>
<p>Questa lista di libri è caricata dinamicamente
dal <strong>database</strong> con <strong>AJAX</strong>!</p>
<div id="myDivElement"></div>
</div>
</div>
</body>
</html>
mysql_3.js
// JavaScript Document
// contiene il riferimento all'oggetto XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// ritrova l'oggetto XMLHttpRequest
function createXmlHttpRequestObject() {
// contiene il riferimento all'oggetto XMLHttpRequest
var xmlHttp;
// se il browser è Internet Explorer 6 o più vecchio
if(window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
}
// se è Mozilla o altri
else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
// ritorna l'oggetto o errore
if (!xmlHttp) {
alert("Error creating the XMLHttpRequest object.");
} else {
return xmlHttp;
}
}
function process() {
// se esiste l'oggetto
if (xmlHttp) {
// cerca di connetterti al server
try {
// chiamo il file php
xmlHttp.open("GET", "index.php", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
// messaggio di errore
catch (e) {
alert("Can't connect to server:\n" + e.toString());
}
}
// funzione chiamata al variare di onreadystatechange
function handleRequestStateChange() {
// quando readyState è 4, la risposta è completata
if (xmlHttp.readyState == 4) {
// controllo che lo stato della richiesta sia OK
if (xmlHttp.status == 200) {
try {
// fai qualcosa con la risposta del server
handleServerResponse();
} catch(e) {
// mostra un messaggio di errore
alert("Error reading the response: " + e.toString());
}
} else {
// mostra un messaggio di stato
alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
}
}
}
// gestisce la risposta del server
function handleServerResponse() {
// leggo la risposta con una libreria
responseJSON = JSON.parse(xmlHttp.responseText);
// genero HTML output
var html = "";
// itero nell'array e creo HTML
for (var i=0; i<responseJSON.books.length; i++)
html += responseJSON.books[i].title + "<br/>";
// ottengo una refernce al contenitore
myDiv = document.getElementById("myDivElement");
// inserisco l'HTML
myDiv.innerHTML = "<p>Server says: </p>" + html;
}
config.php
<?
// defines database connection data
define('DB_HOST', 'localhost');
define('DB_USER', 'ajax_course_2010');
define('DB_PASSWORD', 'ajax_course_2010');
define('DB_DATABASE', 'ajax_course_2010');
?>
error_handler.php
<?php
// assegno la funzione di base per gestire gli errori
set_error_handler('error_handler', E_ALL);
// definisco funzione per gli errori
function error_handler($errNo, $errStr, $errFile, $errLine) {
// pulisco ogni output già generato
if(ob_get_length()) ob_clean();
// fai l'output dell'errore
$error_message = 'ERRNO: ' . $errNo . chr(10) .
'TEXT: ' . $errStr . chr(10) .
'LOCATION: ' . $errFile .
', line ' . $errLine;
echo $error_message;
exit;
}
?>
index.php
<?php
header('Content-Type: text/json');
// includi i file
require_once('error_handler.php');
require_once('config.php');
// connettiti al database
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// formula la query
$query = 'SELECT book_id, book_title FROM books';
// esegui la query
$result = $mysqli->query($query);
$books = array();
// cicla sul risultato
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
// estrai book id e title
$book_id = $row['book_id'];
$book_title = $row['book_title'];
$book = array('title' => $book_title,'id' =>$book_id);
array_push($books, $book);
}
$response = array('books' => $books);
// encodo l'array in JSON
echo json_encode($response);
// chiudi l'input stream
$result->close();
// chiudi la connessione al db
$mysqli->close();
?>