Database Abstraction Layer for PHP

User Tools

Site Tools


Key/Value Pairs

An Associative Array

An often-used SQL construction is to read a table for a key/value pair. This can be used in creating Select Boxes, Radio groups etc. ADOdb contains a shortcut command getAssoc() to assist in the task.

$sql = "select emp_no, emp_name from employees";
$array = $db->getAssoc($sql);
* Returns
1000 =>'Joe Smith',
1001 =>'Fred Jones'
1002 => 'Arthur Dent'

Supplying Data To An Ajax Client

PHP routines are often used to provide data to Javascript frameworks, such as Jquery. The data is often returned in JSON format, which can easily be created using ADOdb. The sample program below provides data to the Jquery plugin Select2 which creates replacement Select Boxes.

Client Side Code

On the client side, the javascript code is defined to use an Ajax server

  ajax: {
    url: "",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, 
    definition continues.........

Server Side Code

On the server side, we query a table containing USA State codes and names.

* Program adodbExample.php
include_once 'adodb_dir/';
* We define a simple object to represent the data,
* plus an array to hold them in
class jsonObject
    * The jquery plugin requires each pair of data be a json object,
    * with the key called 'id' and the description called 'text'
    public $id;
    public $text;
$rows = array();
$db = newAdoConnection('mysqli');
$sql = "SELECT state_code,name 
         FROM us_states
     ORDER BY state_code";
$result = $db->execute($sql);
while ($r = $result->fetchRow())
    $o       = new jsonObject;
    $o->id   = $r[0];
    $o->text = $r[1];
    $rows[]  = $o;
* Return the data to the calling progam
    header('Content-Type: application/json');
print json_encode($rows);

Other Methods For Ajax

The method fetchNextObject() returns data as a PHP object which can be easily JSON encoded.

v5/userguide/learn_abstraction/key_value_pairs.txt · Last modified: 2021/02/21 13:45 by peterdd