Login Register

Bringing PHP, MySQL, and Dojo together

I made a pact that I’d add documentation on how to use PHP, MySQL, and Dojo together, when finishing the Dojo ItemFileReadStore demo. It’s not easy to format a JSON specific file with PHP, which includes special characters and requires JSON members. With several PHP JSON encoders out there, I recommend using the PHP encoder which came bundled with the toolkit (dojo/tests/resources/JSON.php).

Before I cut to the code, let me emphasize formatting the members,“identifier and label”, had me stumped. After tinkering with arrays and trying different encoders, I solved the puzzle by using the JSON.php file that came with the Dojo Toolkit. This file above all other encoders, allowed me format the JSON data just enough to implement the Dojo / Data / ItemFileReadStore demo. If you look closely at the colons and single quotes below, this had me swinging for hours in the sand trap.

identifier: 'name', label: 'name',

My example here is adapted from the campus, but uses Pizza instead of countries. It covers the basics when getting started with PHP, MySQL and Dojo. Hopefully it helps demystify how to format MySQL data with PHP so you can use Dojo to light up your screen lightening fast. Oh one other issue worth noting is your data. If the data source contains two or more records, which will result in identical name:value JSON’s pairs, you are likely to have an issue parsing the data to your page. Look at Redlands and Redlands1, as a solution.

Part 1- Putting Together a Database Using MySQL Command Prompt

mysql> USE DOJO_db;

mysql> CREATE TABLE PIZZA_tbl
-> (ID int not null auto_increment,
-> NAME varchar(45) not null,
-> TYPE varchar(20) not null,
-> FEATURE_ID varchar(20) not null,
-> PRIMARY KEY(ID));

mysql> CREATE TABLE PLACES_tbl
-> (ID int not null auto_increment,
-> NAME varchar(45) not null,
-> TYPE varchar(20) not null,
-> FEATURE_ID varchar(20) not null,
-> PRIMARY KEY(ID));

mysql> INSERT INTO PIZZA_tbl (NAME,TYPE,SSN) VALUES
->("Tony's Pizza","Pizza","877654"),
->("Meg's Pizza","Pizza","880559"),
->("Doogle's Pizza","Pizza","1182332"),
->("Redlands's Pizza","Pizza","252966"),
->("New York Pizza","Pizza","252966");

mysql> INSERT INTO PLACES_tbl (NAME,TYPE,FEATURE_ID) VALUES
->("Lambertville","Place","877654"),
->("Ship Bottom","Place","880559"),
->("New Hope","Place","1182332"),
->("Redlands","Place","252966"),
->("Redlands1","Place","252966");

Part 2- Getting Data Out of MySQL with PHP and Formatting it into JSON

<?php
//*Note title this basic.php
//*Note uppercase variables kill MDB2 queries
include_once('../includes/scripts/dojo_dug/dojo/tests/resources/JSON.php'); //Included with Dojo

//SQL select function
function select($val1,$val2,$val3,$table1)
{
        global $data_array;
        require_once 'MDB2.php'; //I use PEAR MDB2 database abstration PHP extention

        $dsn = array(
            'phptype'  => 'mysql',
            'username' => 'username',
            'password' => 'password',
            'hostspec' => 'localhost',
            'database' => 'DOJO_db',
        );

        $options = array(
            'debug'       => 2,
            'portability' => MDB2_PORTABILITY_ALL,
        );
        // uses MDB2::factory() to create the instance
        // and also attempts to connect to the host
        $mdb2 =& MDB2::connect($dsn, $options);
        if (PEAR::isError($mdb2)) {
            die($mdb2->getMessage());
        }
        $mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC);
        $res =& $mdb2->query("SELECT $val1,$val2,$val3 FROM $table1");
        $i = 0;
        
        while (($row = $res->fetchRow()))
        {
       $node = array(
          'name'=> "".$row[$val1],
          'type'=> $row[$val2],
       );
           $data_array[$i] = $node;
       $i++;
   }
   return $data_array;
}

////Create Variables For Query 1////
$val1= "name";
$val2= "type";
$val3= "feature_id";
$table1= "pizza_tbl";

select($val1,$val2,$val3,$table1); //Call function
$a = $data_array; //Store pizza (MySQL) data as $a

////Create Variables For Query 2////
$val1= 'name';
$val2= 'type';
$val3= 'feature_id';
$table1= 'places_tbl';

select($val1,$val2,$val3,$table1); //Call function
$b = $data_array; //Store places (MySQL) data as $b

///Bring both MySQL queries together in single array
   $c = $a
    while(list(,$v)=each($b)) {
        $c[] = $v;
    }
//Encode as JSON using tool packaged with Dojo
$json = new Services_JSON(); //Dojo class
$data = $json->encode(array('identifier'=>'name','label'=>'name', 'items'=>$c));
echo $data;
?>

Part 3- A repeat of the Dojo / Data / ItemFileReadStore/ Basic Example

(http://dojocampus.org/explorer/#Dojo_Data_ItemFileReadStore_Basic)

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Doog's Page</title>
   <!-- CSS -->
   <style type="text/css">
     @import "../includes/scripts/dojo_dug/dojo/resources/dojo.css";
     @import "../includes/scripts/dojo_dug/dijit/themes/tundra/tundra.css";
   </style>

   <link rel="stylesheet" href="../includes/styles/form.css" type="text/css" />

   <script type="text/javascript"
   src="../includes/scripts/dojo_dug/dojo/dojo.js"
  </script>

 
<script type="text/javascript">
  dojo.require("dijit.form.Button");
  dojo.require("dojo.data.ItemFileReadStore");
 
  //Create a new data store
  var countryStore = new dojo.data.ItemFileReadStore({url: "basic.php"});
  //This function writes the retrieved data to a DIV, and is attached
  //to the 'onComplete' event in the request object
  var gotContinents = function(items, request){
    var buffer = ["<b>Show Pizza and Places</b>"];
      for (var i = 0; i < items.length; i++){
          //alert(items.length)
         var item = items[i];
       buffer.push(countryStore.getLabel(item));
      }
      dojo.byId("dataOutput").innerHTML = buffer.join("");
    //dojo.byId("dataOutput").innerHTML = buffer.join("");
  }
  //This query finds all items that have a 'type' attribute set to 'continent'
  var queryPlaces = {type:"place"};
  //This query finds all items that have a 'type' attribute set to 'country'
  var queryPizza = {type:"pizza"};
  //Fetch the data.
  var getData = function(query){
    countryStore.fetch({query: query, onComplete: gotContinents});
  };

</script>

</head>
<body>
<h2>Dojo/ Data / ItemFileReadStore demo </h2>
<h3>Using PHP, JSON and MySQL</h3>
<button dojoType="dijit.form.Button" onclick="getData(queryPlaces);">Find places</button>
<button dojoType="dijit.form.Button" onclick="getData(queryPizza);">Find pizza</button>

<div id="dataOutput">
  The retrieved data is written here
</div>
</body>

I encourage others to post here PHP, MySQL,JSON and Dojo Dojo / Data / ItemFileReadStore information.

Best,
Doogle
http://dbarrettcarroll.com
http://esri.com

Thank you very much for

Thank you very much for posting this information. I have to say I probably would have never figured this out with just the existing toolkit documentation. The only difference in my approach is that I used the json_encode function native to PHP version 5.2 instead of the bundled JSON.php.

Thanks again,
-Zach Todd

json_encode

I also use the php native json_encode function which is written in C. It's super fast at encoding objects into json.

PHP + DOJO + DB

Hi,

Im using PHP + ZF + DOJO (not the build-in ZF) + DB

All "controllers" like DB (Oracle, Mysql, Postgres...) and JSON are maded by the ZF and I have to say that im geting a very good result...

At the view layer im using "plain" dojo + php and NOT the default ZF Dojo and the result is a more flexible and (kinf of) "PHP independant" view layer...

PHP Frameworks Examples (Zend and PEAR)

I too just jumped into the Zend Framework. I really like it because I wanted abstraction that supports SQLite3. However, I am doubtful that I am implementing the Model Controller View correctly. Especially when executing queries via dojo.data.ItemFileReadStore. If you have time, can you share a simple example how you do this with Zend Framework?

In particular, I am concerned that my file system for implementing this is all wrong. From what I read it seems you need to have your query functions in the applications/controller directory? Also I have read that the header and footer files are in the application/views file? I think I may be making this more complicated then necessary! That said, I just want to implement the Model Controller View correctly.

Any type of sample that shows how to use the Zend_db Framework with Dojo would be great! I will be glad to share my code, but like I said I am just not sure my execution is correct. Thanks to all those he have posted here. I will re-review how to use the json_encode function native to PHP when making JSON.

itemfilereadstore doesnt work with php and IE

That works with firefox, but when using Internet Explorer,
it doesnt work!

What could be wrong?

Example with ComboBox
http://www.dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/combobox-...

Example with Grid:
http://www.dojotoolkit.org/forum/dojox-dojox/dojox-grid-support/cant-loa...