<- v5:userguide:learn_abstraction:basic_query|A Basic Query ^ v5:userguide:learn_abstraction:start_lesson|Start Of Lesson ^ v5:userguide:learn_abstraction:using_execute|Using The Execute Method -> ~~NOTOC~~ ====== 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 [[v5:reference:connection:getassoc|getAssoc()]] to assist in the task. $sql = "select emp_no, emp_name from employees"; $array = $db->getAssoc($sql); print_r($array); /* * Returns */ array( 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 [[https://select2.github.io/|Select2]] which creates replacement Select Boxes. ==== Client Side Code ==== On the client side, the javascript code is defined to use an Ajax server (".js-data-example-ajax").select2({ ajax: { url: "http://127.0.0.1/adodbExample.php", 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/adodb.inc.php'; /* * 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'); #$db->debug=true; $db->connect('dbhost','dbuser','dbpassword','dbname'); $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 */ if(!$db->debug){ header('Content-Type: application/json'); } print json_encode($rows); ===== Other Methods For Ajax ====== The method [[v5:reference:recordset:fetchnextobj|fetchNextObject()]] returns data as a PHP object which can be easily JSON encoded. {{htmlmetatags>metatag-keywords=(php, programming, json, javascript, jquery, adodb, select2, plugin, ajax)}} {{htmlmetatags>metatag-description=(An example of how to use ADOdb to serve a jquery plugin using ajax )}}