Rewrite manually created nested JSON to use PHPs built in functions - php

I have in my table records that are related one to another by a parentId field. When fetching them from the DB I need to create JSON array of objects where the child records are added to 'children' property of parent objects :
[{
//main object
children : [
{
//#1st level children object
children: [
{
//#2nd level children object
}
]
}
]
},
{
(...)
]
But if there are no records with parentId equal to current record, then this property shouldn't be added to the object.
Right now I'm building the JSON string manually :
//first get the parents
$q = 'SELECT * FROM table WHERE parentId = 0';
$r = mysql_query($q);
$x=1;
$nr = mysql_num_rows($r);
while($e = mysql_fetch_array($r)){
if($x==1){
echo '[ { ';
}
else{
echo ' { ';
}
if($e['leaf']==1){
$leaf = 'true';
} else {
$leaf = 'false';
}
echo '"EndDate" : "'.str_replace('T00:00:00','',$e['EndDate']).'",
"Id" : '.$e['Id'].',
"Name" : "'.$e['Name'].'",
"BaselineStartDate" : "'.str_replace('T00:00:00','',$e['BaselineStartDate']).'"';
if($leaf){
echo ',"leaf": '.$leaf.'';
}
childs($e['Id'], $x, $nr);
if($x<$nr){
echo ',';
}
$x++;
}
if($x>1){
echo ']';
}
function childs($id, $x, $nr, $x2='', $nr2=''){
//now see if there are childern
$q2 = 'SELECT * FROM table WHERE parentId = "'.$id.'" ';
$r2 = mysql_query($q2);
$nr2 = mysql_num_rows($r2);
if($nr2>0){
echo ',"children": [ ';
$x2 =1;
while($e2 = mysql_fetch_array($r2)){
if($e2['leaf']==1){
$leaf2 = 'true';
}
else{
$leaf2 = 'false';
}
echo '{
"EndDate" : "'.str_replace('T00:00:00','',$e2['EndDate']).'",
"Id" : '.$e2['Id'].',
"Name" : "'.$e2['Name'].'",
"BaselineStartDate" : "'.str_replace('T00:00:00','',$e2['BaselineStartDate']).'",
"leaf" : "'.$leaf2.'"';
childs($e2['Id'],$x,$nr,'',$x2,$nr2);
if($x2<$nr2){
echo ',';
}
$x2++;
}
echo '] }';
}
else{
echo ',"children" : []}';
}
}
Is there an easy way to make this code more robust using some built-in PHP features like fetch_assoc or something like that?

You should rather..
Fetch the results from the database
Reformat as per the requirement (related code you can use with some alteration PHP Create a Multidimensional Array from an array with relational data
Then finally, json_encode the resulting array

Related

How to Insert a JSON code with PHP & SQL?

I am trying to Insert my Categories SQL tables with a JSON in the below format.
[
{"id":21, "children": [{"id":4},{"id":7}]},
{"id":6},
{"id":5},
{"id":20},
{"id":10},
{"id":9}
]
I have tried to make it possible with this Code:
if(isset($_POST['category'])){
if(in_array($_GET['key'], $_SESSION['key'])){
unset($_SESSION['key'][array_search($_GET['key'], $_SESSION['key'])]);
$i = 1;
$rootof = array();
foreach($_POST['category'] as $cat => $parent){
if($parent == 'children'){
$p = "NULL";
$root = "NULL";
}else{
$p = intval($parent);
if(isset($rootof[$p])){
$root = $rootof[$p];
$rootof[intval($cat)] = $rootof[$p];
}else{
$root = $p;
$rootof[intval($cat)] = $p;
}
}
mysqli_query($db, "UPDATE ads_categories SET category_order = $i, category_parent = $p, category_root = $root WHERE category_id = ".intval($cat));
$i++;
}
echo 'Success';
}else{
echo 'Error';
}
}
I expect Saving the Categories by Id and subcategories (children) to Database.
I want to Insert Id 21, 6, 5 to categories->id,
if array has Children it means that it has subcategories.
subcategories has category_parent id to main category
Example: Categorie ID 4 category_parent would be 21

Notice: Trying to get property of non-object in in json

<?php
$json= '{
"fields" :
[
{
"name" : "news_title",
"type" : "text",
"value" : "old title"
},
{
"name" : "news_content",
"type" : "textarea",
"value" : "old content"
}
]
}';
echo $json;
$jsonInPHP = json_decode($json,true);
$results = count($jsonInPHP['fields']);
for ($r = 0; $r < $results; $r++){
// look for the entry we are trying to find
if ($jsonInPHP->fields[$r]['name'] == 'news_title'
&& $jsonInPHP->fields[$r]->value == 'old title'){
// remove the match
unset($jsonInPHP->fields[$r]);
if(empty($jsonInPHP->fields[$r]->value))
{
$jsonInPHP['fields'][$r]['name'] == 'news_title';
$jsonInPHP->fields[$r]->value=='no';
}
break;
}
}
function gog($status)
{
$results = count($status->fields);
for ($r = 0; $r < $results; $r++){
$status->fields[$r]->value == 'old rr';
}
}
$jsonInPHP->fields = array_values($jsonInPHP->fields);
echo json_encode($jsonInPHP);
?>
i want to change after searching from
'{"fields":[{"name":"news_title","type":"text","value":"old title"},{"name":"news_content","type":"textarea","value":"old content"}]}'
to
'{"fields":[{"name":"news_title","type":"text","value":"My new title"},{"name":"news_content","type":"textarea","value":"My new content"}]}'
Check official docs of json_decode Second parameter of function json_decode($json,true); (in your case true) determines whether result will be converted to associative array. If you want to use result as objects set that value to false or better omit that at all.

Symfony2 - Am I handling things in the correct place?

I am in the process of turning my standard PHP project into something built on Symfony2. One part I have is this function
function viewAvailability(){
$db = Database::get();
$active = "Active";
// Fetch all the active alert IDs.
$idListSql = $db->prepare("SELECT DISTINCT id
FROM availability_alert
WHERE alert_status = :active");
$idListSql->bindParam(':active', $active);
$idListSql->execute();
$alerts = array();
// Go through each ID.
while ($idListRow = $idListSql->fetch(PDO::FETCH_ASSOC)) {
$alertId = (int)$idListRow["id"];
// Create the first dimension of the array, using the alert ID as the key.
$alerts[$alertId] = array();
// Fetch all the availability values for this alert.
$availabilitySql = $db->prepare("
SELECT availability, last_updated, class_letter, alert_pseudo, flight_number
FROM availability_alert_availability
WHERE availability_alert_id = {$alertId}
ORDER by class_letter, last_updated");
$availabilitySql->execute();
// Go through each availability result.
while ($aRow = $availabilitySql->fetch(PDO::FETCH_ASSOC)) {
// Fetch the date and hour for this availability row as a string.
$dateString = new DateTime($aRow["last_updated"]);
$dateString = $dateString->format('d M Y H:00');
// Create the second dimension of the array, using the alert pseudo as the key.
if (empty($alerts[$alertId][$aRow["alert_pseudo"]])) {
$alerts[$alertId][$aRow["alert_pseudo"]] = array();
}
// Create the third dimension of the array, using the flight number as the key.
if (empty($alerts[$alertId][$aRow["alert_pseudo"]][$aRow["flight_number"]])) {
$alerts[$alertId][$aRow["alert_pseudo"]][$aRow["flight_number"]] = array();
}
// Create the fourth dimension of the array, using the date string as the key.
if (empty($alerts[$alertId][$aRow["alert_pseudo"]][$aRow["flight_number"]][$dateString])) {
$alerts[$alertId][$aRow["alert_pseudo"]][$aRow["flight_number"]][$dateString] = array();
}
// Create the fifth dimension of the array, using the class letter as a key, and the
// availability value as the value.
$alerts[$alertId][$aRow["alert_pseudo"]][$aRow["flight_number"]][$dateString][$aRow["class_letter"]] = $aRow["availability"];
}
}
}
This is only part of the function, I then go onto a lot of loops to output the data in a table. Anyways, I have moved my database calls above into my Entities custom repository (using DQL instead).
I then do most of the above working in my controller
public function availabilityAction()
{
$em = $this->getDoctrine()->getEntityManager();
$alerts = $em->getRepository('NickAlertBundle:AvailabilityAlert')->getActiveAlertIds();
$alertsArray = array();
if (!$alerts) {
throw $this->createNotFoundException('Unable to find Availability.');
}
foreach($alerts as $alert){
$alertId = (int)$alert['id'];
$alertsArray[$alertId] = array();
$allAvailability = $em->getRepository('NickAlertBundle:AvailabilityAlert')->getAlertAvailability($alertId);
foreach($allAvailability as $alertAvailability)
{
$dateString = $alertAvailability['lastUpdated'];
$dateString = $dateString->format('d M Y H:00');
if (empty($alerts[$alertId][$alertAvailability['alertPseudo']])) {
$alertsArray[$alertId][$alertAvailability['alertPseudo']] = array();
}
if (empty($alerts[$alertId][$alertAvailability['alertPseudo']][$alertAvailability['flightNumber']])) {
$alertsArray[$alertId][$alertAvailability['alertPseudo']][$alertAvailability['flightNumber']] = array();
}
if (empty($alerts[$alertId][$alertAvailability['alertPseudo']][$alertAvailability['flightNumber']][$dateString])) {
$alertsArray[$alertId][$alertAvailability['alertPseudo']][$alertAvailability['flightNumber']][$dateString] = array();
}
$alertsArray[$alertId][$alertAvailability['alertPseudo']][$alertAvailability['flightNumber']][$dateString][$alertAvailability['classLetter']] = $alertAvailability['availability'];
}
}
return $this->render('NickAlertBundle:Page:availability.html.twig', array(
'alertsArray' => $alertsArray,
));
}
Now it is a lot neater, but I feel there is too much going on in my controller (not sure if this is good or not). The other problem is that I am then passing this filled up array I have to my view. Now I have a complex table layout to create from this array, and I really dont think it should be the job of the view to do this. As an example, this is part of the code I would need to convert within the view
if (!empty($pseudos)) {
foreach ($pseudos as $pseudo => $flights) {
foreach ($flights as $flight => $dates) {
$firstDate = array_pop(array_keys($dates));
echo '<div class="availability_table_container">';
echo "<table class='availability_table'>";
echo "<tr>";
if ($i == 0) {
echo "<th></th>";
}
echo "<th class='pseudo-header'>{$flight}</th>";
echo "</tr>";
echo "<tr>";
foreach (array_keys($dates[$firstDate]) as $classLetter) {
if ($j == 0) {
echo "<th></th>";
}
$j++;
echo "<th class='class-header'>{$classLetter}</th>";
}
echo "</tr>";
foreach ($dates as $date => $classes) {
echo "<tr>";
if ($i == 0) {
echo "<td class='time_row'>{$date}</td>";
}
foreach ($classes as $classLetter => $availability) {
if ($availability >= 0) {
$className = $availability > 0 ? "green" : "red";
}
if ($availability == "." || $availability == "-") {
$className = "purple";
}
echo "<td class='number_row {$className}'>{$availability}</td>";
}
echo "</tr>";
}
$i++;
echo "</table>";
echo "</div>";
}
}
}
So what's the best way to handle this code? I think I am right in not allowing my view to handle the above code, but then where should I do it?
Any advice on the design is appreciated.

PHP : SQL request works fine but return text = null for some element

My PHP script works fine, but for some element, i get null values whereas in the table the text is well here :
[
{
"etat":"online",
"nb_visiteurs":"0",
"id":"1",
"date_debut":"19\/05\/2014",
"prix":"40",
"description":null,
"id_author":"1",
"titre":null
},
{
"etat":"online",
"nb_visiteurs":"0",
"id":"2",
"date_debut":"21\/05\/2014",
"prix":"30",
"description":null,
"id_author":"1",
"titre":null
},
{
"etat":"offline",
"nb_visiteurs":"0",
"id":"3",
"date_debut":"22\/05\/2014",
"prix":"23",
"description":"TOP NOIR STYLE ASIATIQUE EN BON ETAT T 3\r\n\r\nFAIRE PROPOSITION",
"id_author":"1",
"titre":"Top noir style asiatique en bon etat t3"
},
{
"etat":"online",
"nb_visiteurs":"0",
"id":"4",
"date_debut":"22\/05\/2014",
"prix":"45",
"description":null,
"id_author":"1",
"titre":"Lit+sommier+matelas+ table de chevet+commode"
}
]
Here is the content of my annonces table :
And here is the structure of the table :
<?php
$PARAM_hote='aaaaaa';
$PARAM_port='3306';
$PARAM_nom_bd='bbbbbbbbb';
$PARAM_utilisateur='ccccccccc';
$PARAM_mot_passe='dddddddddd';
// Create connexion to BDD
$connexion = new PDO('mysql:host='.$PARAM_hote.';port='.$PARAM_port.';dbname='.$PARAM_nom_bd, $PARAM_utilisateur, $PARAM_mot_passe);
try {
// Getting username / password
$username = $_POST['username'];
$password = $_POST['password'];
// Prepare SQL request to check if the user is in BDD
$result1=$connexion->prepare("select * from tbl_user where username = '".$username."' AND password = '".$password. "'");
$result1->execute();
// Getting all results in an array
$arrAllUser = $result1->fetchAll(PDO::FETCH_ASSOC);
// If the size of array is equal to 0, there is no user in BDD
if (sizeof($arrAllUser) == 0) {
echo "fail";
}
// In this case, a user has been found, create a JSON object with the user information
else {
// Getting id of the user
$id_user = $arrAllUser[0]['id'];
// Prepare a second SQL request to get all annonces posted by the user
$result2=$connexion->prepare(" select * from annonces where id_author = '".$id_user."' ");
$result2->execute();
// Getting all annonces posted by the user in an array
$arrAllAnnonces = $result2->fetchAll(PDO::FETCH_ASSOC);
// Set in key user the USER structure
$array['user'] = $arrAllUser[0];
// Set in key annonces all annonces from the user
$array['annonces'] = $arrAllAnnonces;
// JSON encore the array
$json_result = json_encode($array);
echo $json_result;
}
} catch(Exception $e) {
echo 'Erreur : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
}
?>
It's happening because french letters, the function fails to parse them.
try to use flag JSON_UNESCAPED_UNICODE
json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE)
you can play with the flags
try this
$output = array();
foreach ($array as $row)
{
$output[]=array_map("utf8_encode", $row);
}
$json_result = json_encode($output);
echo $json_result;
agree with volkinc answer,if you have a new php version you can use
json_unescaped_unicode instead of json_encode
and if your php version 5.3 and older unescaped wont work , just add this function at the bottom of the script and use it instead of json_encode
function my_json_encode($in) {
$_escape = function ($str) {
return addcslashes($str, "\v\t\n\r\f\"\\/");
};
$out = "";
if (is_object($in)) {
$class_vars = get_object_vars(($in));
$arr = array();
foreach ($class_vars as $key => $val) {
$arr[$key] = "\"{$_escape($key)}\":\"{$val}\"";
}
$val = implode(',', $arr);
$out .= "{{$val}}";
}elseif (is_array($in)) {
$obj = false;
$arr = array();
foreach($in AS $key => $val) {
if(!is_numeric($key)) {
$obj = true;
}
$arr[$key] = my_json_encode($val);
}
if($obj) {
foreach($arr AS $key => $val) {
$arr[$key] = "\"{$_escape($key)}\":{$val}";
}
$val = implode(',', $arr);
$out .= "{{$val}}";
}else {
$val = implode(',', $arr);
$out .= "[{$val}]";
}
}elseif (is_bool($in)) {
$out .= $in ? 'true' : 'false';
}elseif (is_null($in)) {
$out .= 'null';
}elseif (is_string($in)) {
$out .= "\"{$_escape($in)}\"";
}else {
$out .= $in;
}
return "{$out}";
}
and use my_json_encode instead of json_encode and dont forget this line :
header('content-type:text/html;charset=utf-8');
thanks to the person who made this function i forgot from where i got it.

Is there a free PHP Wrapper or backend script for a JQUERY Grid Control (JQGRID or Datatables)

I am looking to implement a best-practice JQUERY grid control, with a PHP backend. I want it to be able to support large datasets, and inline cell editing.
I am struggling to find a PHP backend script which is integrated with the control and abstracts away the complexities of this stuff. I want to be able to implement a grid based on an underlying MYSQL table with a minimum of configuration. Really I can't be the only one who wants to be able to specify basic database details and table/sql and have an operating grid.
JQGrid has a paid PHP script backend you can use which sounds like what I want...only its expensive.
http://www.trirand.net/documentation/php/index.htm
There's also a cheaper thing trying to do the same thing, but it doesn't work.
http://azgtech.wordpress.com/2010/08/01/jqgrid-php-datagrid/
I've also looked at DataTables, but once you add the inline-editing capabilities, developing the PHP backend started becoming its own project.
I have spend ages researching this, and mucking about with various solutions.
Does anybody know of a powerful, free, easy to use solution which has a complete PHP backend script?
I've included some of the description of the paid JQGrid PHP control, which contains the kind of functionality I'm looking for.
JQGRid PHP
This is a brand new product created for PHP developers and teams that radically decreases development time with jqGrid and makes it fun and easy. The product will be offered with commercial licenses that will include fast and accurate technical support, source code and subscription based benefits.
Highlight points include:
- all functionality jqGrid has is supported
- no need for tricky javascript – everything is handled in PHP
- the PHP component automatically handles data retrieval, paging, sorting, searching and all CRUD operations (create, read, update, delete). No need for custom code.
- you can have a fully functional grid with just a few lines of PHP
- export to Excel is supported
- database engines supported: MySql, Postgre SQL, Microsoft SQL server
Have you checked out phpGrid. It's a PHP jqgrid wrapper. It just two lines of code to get started. Is that something you are looking for?
$dg = new C_DataGrid(“SELECT * FROM orders”, “orderNumber”, “orders”);
$dg -> display();
I wrote this small library a while back as a a booze filled weekend project a while ago, it's a bit messy but it'll provide some of the default back end functionality that you're looking for.]
<?php
/*
Grid.php
Lirbary of function for the translation of Array() objects into json
*/
/*--- INCLUDE DEPENDENCIES ---*/
include_once "lib/sql.php";
/*--- HEADER UPDATE ---*/
header("Content-type: application/json");
/*--- GLOBALS ---*/
/*Default sort order*/
define('GRID_DEFAULT_SORT_ORDER', "ASC");
/*Default page index*/
define('GRID_DEFAULT_PAGE', 0);
/*Default results per page*/
define('GRID_DEFAULT_RP', 15);
/*--- FUNCTIONS ---*/
/*
Build Grid Queries
desc: Build the queries used to provide the grid results
params:
$select: 2D associative array
field: name of field
alias: field alias
$from: table data is to be selected from
return: An array containing the query to select entries and the query to get the result count
*/
function buildGridQueries($select, $from)
{
/*Create select statement*/
$selectStr = "SELECT ";
for($i = 0; $i < count($select);$i++){
/*append field name to str*/
$selectStr .= $select[$i]['field'];
/*If an alias has provided*/
if(isset($select[$i]['alias']))
$selectStr .= " AS '". $select[$i]['alias']. "'";
/*if current field is not the last */
if($i < count($select) - 1)
$selectStr .= ", ";
}
/*Create from statement*/
$fromStr = " FROM $from";
/*Set sort by value by $_POST value if available or by $select[0][field]*/
$sortStr = " ORDER BY ";
if(isset($_POST['sortname']))
if($_POST['sortname'] == "undefined")
$sortStr .= $select[0]['field'];
else
$sortStr .= $_POST['sortname'];
else
$sortStr .= $select[0]['field'];
/*Set sort order by $_POST if available or by ASC*/
if(isset($_POST['sortorder']))
$sortStr .= " ". $_POST['sortorder'];
else
$sortStr .= " ". GRID_DEFAULT_SORT_ORDER;
/*Set query conditional WHERE statement if passed*/
$queryStr = "";
if(isset($_POST['qtype'])&&isset($_POST['query']))
if($_POST['query']!= "")
$queryStr .= " WHERE ". $_POST['qtype']. " LIKE '%" . $_POST['query']. "%' ";
/*Create limit statement by passed values or by defaults*/
$limitStr = " LIMIT ";
if(isset($_POST['page']))
if($_POST['rp'])
$limitStr .= ($_POST['page'] - 1) * $_POST['rp'] . ",". $_POST['rp'];
else
$limitStr .= $_POST['page'] . ", ". GRID_DEFAULT_RP;
else
$limitStr .= GRID_DEFAULT_PAGE. ", ". GRID_DEFAULT_RP;
/*return queries array*/
return Array("query" => $selectStr. $fromStr. $queryStr. $sortStr. $limitStr,
"count" => "SELECT COUNT(id) AS 'total' $fromStr $queryStr ");
}
/*
Commit Data
desc: Commit data edits (Passed by a client side flexigrid object
params:
$table: table name
$rows: rows array of data to be committed
$index: Field name of index column, used in where statement
return: An array of update results for each passed row;
*/
function commitGridData($table,$rows,$indexField, $sqlConnection)
{
/*Declare return array*/
$return = Array();
/*With every row which is to be committed*/
foreach($rows as $row){
/*Create update statement base and iterate through cells*/
$statement = "UPDATE $table SET ";
for($i = 0;$i<count($row['fields']);$i++){
/*If value is a string check to see if it's a date*/
if(!is_numeric( $row['fields'][$i]['value'])){
/*Encapsulate str it isn't a date, convert to time if it is*/
$val = "'". $row['fields'][$i]['value']. "'";
}else
$val = $row['fields'][$i]['value'];
/*Append field name and value to statement*/
$statement .= $row['fields'][$i]['field'] . "=". $val;
/*Append delimiter to the statement if this cell is not the last in $orw*/
if($i<count($row['fields']) - 1)
$statement .= ", ";
}
if($row['entryIndex'] < 0)
$row['entryIndex'] = mysqlCreateEntry($table, $sqlConnection);
/*Append where statement*/
$statement .= " WHERE $indexField = ". $row['entryIndex'];
/*Update row information*/
$return[] = Array("id" => $row['tableId'], "success" => mysqlQuery($statement, $sqlConnection), "error" => mysql_error());
}
/*Return result set*/
return $return;
}
/*
Generate Grid Array
desc: generate Array object which is compatible with FlexiGrid when it is json encoded
params:
$queries: Queries for retrieving data entries and result set size
$fields: 2D associative array or false to prevent inline generation
field: name of field
alias: field alias
$sql: An Sql connection identifier
return: An array of FlexiGrid properties
*/
function generateGridArray($queries, $fields, $sqlConnection)
{
/*Get the total number of results matching the search query*/
$res = mysqlQuery($queries['count'], $sqlConnection);
$total = mysql_fetch_assoc($res);
/*Get matching result set*/
$res = mysqlQuery($queries['query'], $sqlConnection);
/*Create result FlexGrid-compatible Array*/
$data =Array(
"page" => (isset($_POST['page']))? $_POST['page']: 1,
"total" => $total['total'],
"width" => 500,
"height" => (isset($_POST['rp']))? $_POST['rp']: mysql_num_rows($res) * 20 + 45,
"title" => " ",
"propertyCount" => count($fields),
"rows" => sqlToGridRows($fields, $res));
/*If initial request (no $_POST equals passive data collection by the client side*/
if(count($_POST) < 1 ){
$data['colModel'] = sqlToGridColModel($fields, $res);
$data['searchitems'] = arrayToGridSearchItems($fields);
}
/*Return*/
return $data;
}
function sqlToGridRows($fields, $sqlResult)
{
/*Identify the entry index column*/
$fieldTypes = Array();
foreach($fields as $field){
/*if the field is the entry index*/
if(isset($field['entryIndex']))
/*Set field as entryIndex*/
$entryIndexCol = (isset($field['alias']))? $field['alias']: $field['field'];
}
/*Iterate through result set*/
$return = Array();
for($i = 0;$i < mysql_num_rows($sqlResult);$i++){
/*Get entry data*/
$row = mysql_fetch_assoc($sqlResult);
/*modify values based on fieldType*/
foreach($fields as $field){
/*If the fieldType value is set, no changes otherwise*/
if(isset($field['fieldType'])){
/*Field type specific formating*/
switch ($field['fieldType']){
/*Format field as a date*/
case "date":
/*Update by either field label if the label key exists in row or use alias*/
if(isset($row['field']))
$row[$field['field']] = date("d/m/Y", $row[$field['field']]);
else
$row[$field['alias']] = date("d/m/Y", $row[$field['alias']]);
break;
case "time":
if(isset($row['field']))
$row[$field['field']] = date("H:i", $row[$field['field']]);
else
$row[$field['alias']] = date("H:i", $row[$field['alias']]);
break;
}
}
}
/*if the entry index column was identified*/
if(isset($entryIndexCol)){
/*Set entryIndex value*/
$entryIndex = $row[$entryIndexCol];
/*remove the entryIndexCol from the row*/
unset($row[$entryIndexCol]);
}else
/*Set the entry index as the default*/
$entryIndex = $i;
/*Create entry*/
$entry = Array("id" => $i,
"entryIndex" => $entryIndex,
"cell" => $row);
/*iterate $fields and replace aliased keys with field names*/
for($m = 0;$m < count($fields);$m++){
/*if field has an alias update the key value*/
if(isset($fields[$m]['alias'])){
/*Replace and rebuild field->cell*/
$cell = Array();
foreach($entry['cell'] as $key => $val){
/*if culprit cell change key*/
if($key == $fields[$m]['alias'])
$cell[$fields[$m]['field']] = $val;
else
$cell[$key] = $val;
}
/*Update entry->cell value*/
$entry['cell'] = $cell;
}
}
/*Map sql result to grid table row structure*/
$return[] = $entry;
}
/*Return grid-ready array*/
return $return;
}
function sqlToGridColModel($fields, $sqlResult)
{
/*Iterate through result set*/
$return = Array();
for($i = 0;$i < mysql_num_fields($sqlResult);$i++){
/*Replace aliased cell name attributes with associted field name*/
$alias = mysql_field_name($sqlResult, $i);
$name = false;
$isEntryIndex = false;
for($m = 0;$m < count($fields);$m++){
/*If current field has an alias which equals $name, replace name with $field[[$m]['field']*/
if(isset($fields[$m]['alias'])){
/*if field has an alias*/
if($fields[$m]['alias'] == $alias){
$name = $fields[$m]['field'];
}
}else{
if($fields[$m]['field'] == $alias){
$name = $fields[$m]['field'];
}
}
/*Add field data etc*/
$fieldData = false;
if(isset($fields[$m]['fieldType'])){
/*Get field type*/
$fieldType = $fields[$m]['fieldType'];
/*Attach select options to field if available*/
if($fieldType == "select")
/*Set default field type*/
$fieldData = $fields[$m]['fieldData'];
}else
$fieldType = "input";
/*If the field is the entry index flag it for exclusion*/
if($name){
/*If the field is the entry index*/
if(isset($fields[$m]['entryIndex']))
$isEntryIndex = true;
/*Exit for loop*/
$m = count($fields);
}
}
/*If no name was set (alias is also name)*/
if(!$name)
$name = $alias;
/*If the field is to be included in the column model*/
if($isEntryIndex == false){
/*Append column data to return*/
$return[] = Array("display" => $alias, "name" => $name,
"width" => 200, "sortable" => "true",
"fieldType" => $fieldType, "fieldData" => $fieldData);
}
}
/*Return grid-ready array*/
return $return;
}
function arrayToGridSearchItems($fields)
{
/*iterate fields*/
$return = Array();
for($i = 0;$i < count($fields);$i++){
/*if field has an alias use it for the display name*/
$alias = (isset($fields[$i]['alias']))? $fields[$i]['alias']: $fields[$i]['field'];
/*If field is not the entry index*/
if(!isset($fields[$i]['entryIndex']))
/*Create searchitem and append to return*/
$return[] = Array("display" => $alias,
"name" => $fields[$i]['field'],
"isdefault" => ($i == 0)? "true": "false");
}
/*return*/
return $return;
}
?>
This is designed to allow the development of Grid data tables using a standard template, Below is an example template.
<?php
/*include grid lib*/
include "lib/grid.php";
/*Create sql connection*/
$sqlConnection = mysqlConnect($_USER->sqlUser, $_USER->sqlPass);
/*----------------------*/
/*--- Create fieldData ---*/
$userTypes = Array(
Array("value" =>0, "text" => "Staff"),
Array("value" => 1, "text" => "Manager"));
/*----------------------*/
/*---
Define selection array
Create field selection and rules Array. Defines output.
---*/
$array = Array();
$array[] = Array("field" => "id", "entryIndex" => true); /*Entry index is the Sql row id, isn't show in table but is used for commits*/
$array[] = Array("field" => "username", "alias" => "User Name");
$array[] = Array("field" => "name", "alias" => "Name");
$array[] = Array("field" => "address", "alias" => "Address");
$array[] = Array("field" => "postcode", "alias" => "Postcode");
$array[] = Array("field" => "tel", "alias" => "Telephone");
$array[] = Array("field" => "mobile", "alias" => "Mobile");
$array[] = Array("field" => "email", "alias" => "Email Address");
$array[] = Array("field" => "user_type", "alias" => "User Type", "fieldType" => "select", "fieldData" => $userTypes);
$table = "staff";
/*---
Commit data template
Inlcude a the following if
---*/
/*If an action is to be carried out prior to data load*/
if(isset($_GET['method'])){
/*If transaction is a data commit*/
if($_GET['method'] == "commit"){
/*Check that edit requests were sent*/
if(isset($_POST['rows'])){
/*Pre-update validation*/
foreach($_POST['rows'] as &$row){
/*Any preprocessing for entries prior to commit*/
}
echo json_encode(commitGridData($table, $_POST['rows'], "id", $sqlConnection));
exit;
}
}
}
/*Buildd queries - Opportunity to debug queries, alternatively pass to generateGridArray*/
$queryStrs = buildGridQueries($array, "staff");
/*Generate grid data*/
$resArray = generateGridArray($queryStrs, $array, $sqlConnection);
/*Pre grid build extend and/or alter settings*/
if(count($_POST) < 1){
$resArray['buttons'] = Array(Array("name" => "Add", "bclass" => "add", "onpress" => "add"));
$resArray['title'] = "Staff Details";
$resArray['editable'] = true;
}
echo json_encode($resArray);
exit;
?>
I've extended Flexgrid to accommodate for field formatting, committing data and adding field events but I can't for the life of me find it. I'll post it if I do.
Disclaimer: $_POST is used recklessly throughout grid.php. It is recommended that it's replaced with something more fitting.
I've just found a github project which seems to be really great for this: https://github.com/lampjunkie/php-datatables
It provides a wrapper for Jquery Datatables plugin, handles the initial setup and the ajaq data feeds also. It has an object-oriented approach and seems to be very logically designed.
You also can find an example project in the package.

Categories