I have this code - it's not done by me :s and don't have time to replace the deprecated calls.
<?php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();
$db=mysql_connect('localhost','carros_mil1','K-Jw)ureB.}M');
mysql_select_db('carros_mil0',$db);
$nombreListModelo = 'modelo_'.str_replace(" ","_",strtolower($_REQUEST['nombreMarca']));
$sql = "SELECT DISTINCT (identificador) AS id
FROM modelos
WHERE nombre = '".$nombreListModelo."'";
$rs=mysql_query($sql);
$i=0;
while ($row = mysql_fetch_array($rs)) {
$vectorModelo[$i] = $row['id'];
$i++;
}
$sql = "SELECT attribute_id
FROM eav_attribute
WHERE attribute_code = '".$nombreListModelo."'";
$rs = mysql_query($sql);
$row = mysql_fetch_array($rs);
$id1 = $row['attribute_id'];
$sql= "SELECT eao.option_id AS option_id
FROM eav_attribute_option eao, eav_attribute_option_value eaov
WHERE eao.option_id=eaov.option_id AND attribute_id = ".$id1." ORDER BY eaov.value";
$rs=mysql_query($sql);
$retorno = array();
$bandera = true;
while ($row = mysql_fetch_array($rs)) {
$bandera = false;
$sql2= "SELECT value, option_id
FROM eav_attribute_option_value
WHERE option_id = ".$row['option_id']."
ORDER BY value";
$rs2=mysql_query($sql2);
$row2= mysql_fetch_array($rs2);
if ($_REQUEST['bandera']=='vende') {
if (!is_null($row2['value'])) $retorno[$row2['value']] = $row2['value'];
} else {
$existe=false;
for($k=0;$k<count($vectorModelo);$k++) {
if($row2['option_id'] == $vectorModelo[$k]) {
$existe=true;
break;
}
}
if($existe) {
if($_REQUEST['tipo']=='contactenos')
if (!is_null($row2['value'])) $retorno[$row2['value']] = $row2['value'];
else
if (!is_null($row2['option_id'])) $retorno[$row2['option_id']] = $row2['value'];
}
}
}
if($bandera)
$retorno[''] = 'Todos';
header('Content-Type: application/json');
//echo json_encode($retorno);
foreach($retorno as $k => $v) {
printf("%s => %s\n", $k, $v);
}
print_r($retorno);
echo json_encode($retorno);
Since I noticed something strange in the generated json, I added 2 different ways of printing the contents of the array.
The JSON way adds me a null:null entry. The strange case is that I'm checking !is_null($row2['value']) each time I add an element.
When I hit the url under certain parameters, I get:
Elantra => Elantra
Getz => Getz
H1 => H1
i-10 => i-10
New Accent => New Accent
Santa Fé => Santa Fé
Tucson => Tucson
Array
(
[Elantra] => Elantra
[Getz] => Getz
[H1] => H1
[i-10] => i-10
[New Accent] => New Accent
[Santa Fé] => Santa Fé
[Tucson] => Tucson
)
{"Elantra":"Elantra","Getz":"Getz","H1":"H1","i-10":"i-10","New Accent":"New Accent",null:null,"Tucson":"Tucson"}
The first 6 lines correspond to a custom print foreach loop. There's also a print_r call which only shows 6 elements. The 3rd form - which is the actual one I need - shows a null value.
So: Why is $retorno accepting null entries when I check the null condition beforehand? considering this script is full - no missing code here.
(Thanks #Hammerstein - don't know why you didn't write that as an answer).
The problem is that one of such values was not correctly being encoded, since it was not an ANSI value and was not encoded in UTF8. In this way, since "Santa Fé" had a "strange" character, it was encoded as null instead of "Santa F\u00e9".
Tip: Never assume your database is using an utf8_ charset
The solution was to explicitly encode the values when composing the array:
...
$bandera = false;
$sql2= "SELECT value, option_id
FROM eav_attribute_option_value
WHERE option_id = ".$row['option_id']."
ORDER BY value";
$rs2=mysql_query($sql2);
$row2= mysql_fetch_array($rs2);
//ENCODE the values to a good charset
$value = utf8_encode($row2['value']);
$option_id = utf8_encode($row['option_id'])
if ($_REQUEST['bandera']=='vende') {
$retorno[$value] = $value;
} else {
$existe=false;
for($k=0;$k<count($vectorModelo);$k++) {
if($row2['option_id'] == $vectorModelo[$k]) {
$existe=true;
break;
}
}
if($existe) {
if($_REQUEST['tipo']=='contactenos')
$retorno[$value] = $value;
else
$retorno[$option_id] = $value;
}
}
...
Related
I'm having hard time with this issue
I have multiple queries some data appear in other results...
$query = "SELECT * FROM `hotels`";
$result=mysqli_query($connect,$query);
if(mysqli_num_rows($result)>0) {
while($row=mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$queryPhotos="SELECT * FROM hotel_photo WHERE hotel_id = ".$row['id']." ";
$resultPhotos=mysqli_query($connect,$queryPhotos);
while($rowPhotos=mysqli_fetch_assoc($resultPhotos)) {
$photos[] = array(
"imgUrl" => $rowPhotos['img_url'],
"hotel_id" => $rowPhotos['hotel_id']
);
}
$apiResult[] = array(
'hotel_name' => $hotelname,
'hotel_photos' => $photos,
);
}
header('Content-type: application/json');
echo json_encode($apiResult, JSON_NUMERIC_CHECK);
}
This is my hotel database
and my hotel_photos database
Why I'm still seeing 'hotel_id 1' in dubai hotel...?
Thank you so much for your help.
You aren't empting the $photos array in every new iteration for a new hotel. Hence, the previous results also exists in the array. You need to fix as below:
<?php
while($row = mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$photos = []; // add this line
I have two database tables that contain information about land contracts. They are related with land_contract_annual_price.land_contract_id -> land_contract.land_contract_id.
Table 'land_contract'
Table 'land_contract_annual_price'
If a land contract has the value "Rörligt pris" in the field land_contract_price_type, there are related values in the table
land_contract_annual_price. At the moment I'm doing two queries, one to each table. I then merge the results and present the land contract as a nested JSON array like this:
Version 1
[
{
"land_contract_id":118,
"land_contract_name":"Avtalsnamn",
"location_id":71,
"land_contract_link":"",
"land_contract_notes":"",
"land_owner_id":2,
"land_contract_start_date":"2019-07-25",
"land_contract_end_date":"2023-07-25",
"land_contract_terminated":"false",
"land_contract_payment_interval":"Halv\u00e5rsvis",
"land_contract_price_type":"R\u00f6rligt \u00e5rspris",
"land_contract_fixed_annual_price":null,
"land_contract_annual_prices":[
{"year":1, "price":873.00},
{"year":2, "price":77289.00},
{"year":3, "price":8.00},
{"year":4, "price":0.00},
{"year":5, "price":8729.00}
]
}
]
If a land contract has the value "Fast pris" in the field land_contract_price_type, there are no related values in the table
land_contract_annual_price. In that case I present the land contract like this (without the extra array at the end):
Version 2
[
{
"land_contract_id":13,
"land_contract_name":null,
"location_id":null,
"land_contract_link":"https:\/\/www.something.com\/preview\/Sl%C3%A4pvdam%20Edda\/Kddal\/Bddkta\/Besika%20Markavtal%20%20Halmstad%202016-03-08.pdf?role=personal",
"land_contract_notes":"",
"land_owner_id":null,
"land_contract_start_date":"2016-03-08",
"land_contract_end_date":"2026-03-08",
"land_contract_terminated":"true",
"land_contract_payment_interval":"\u00c5rsvis",
"land_contract_price_type":"Fast \u00e5rspris",
"land_contract_fixed_annual_price":"6000.00"
}
]
What I didn't think of, is that this solution is bad when I'm fetchin ALL the land contracts. If I'm going to do a second query to another table whenever a land contract has the value "Rörligt pris" in the field land_contract_price_type, I'm going to do hundreds of extra queries.
Is there a way to create the nested JSON array with one (1) query when a land contract has the value "Rörligt pris" in the field land_contract_price_type?
Thanks!
Below is my current code.
function read($pdo, $Id = null, $ResponseMessage = null) {
$params = [];
$array = [];
$sql = "SELECT lc.Id, lc.Name, lc.LocationId, l.Name AS LocationName, lc.Notes, lc.LandOwnerId, lo.Name AS LandOwnerName, lc.StartDate, lc.EndDate, lc.IsTerminated, lc.PaymentInterval, lc.PriceType, lc.FixedAnnualPrice, lc.Link, lc.Created, lc.Updated, lcap.AnnualPriceYear AS Year, lcap.AnnualPriceAmount AS Amount
FROM LandContract lc
LEFT JOIN Location l ON l.Id = lc.LocationId
LEFT JOIN LandOwner lo ON lo.Id = lc.LandOwnerId
LEFT JOIN LandContractAnnualPrice lcap ON lcap.LandContractId = lc.Id
ORDER BY lc.Id DESC, lcap.AnnualPriceYear DESC
";
if ($Id) {
$sql .= 'WHERE lc.Id = ?';
$params[] = $Id;
}
echo $sql;
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
while ($row = $stmt->fetch()) {
// Fields we want to extract from the select statement into the array
$select_fields = ['Id', 'Name', 'LocationId', 'LocationName', 'Link', 'Notes', 'LandOwnerId', 'LandOwnerName',
'StartDate', 'EndDate', 'IsTerminated', 'PaymentInterval',
'PriceType', 'FixedAnnualPrice ', 'Created', 'Updated'];
if (!isset($array[$row['Id']])) {
// initialize the subarray if it has not been set already
$array[$row['Id']] = array_intersect_key($row, array_flip($select_fields));
if ($row['Year'] != null) {
$array[$row['Id']]['AnnualPrices'] = [];
} else {
$array[$row['Id']]['AnnualPrice'] = $row['FixedAnnualPrice'];
}
}
if ($row['Year'] != null) {
$array[$row['Id']]['AnnualPrices'][] = ['Year' => $row['Year'], 'Amount' => $row['Amount']];
}
}
if (empty($array)) {
$ResponseMessage = new ResponseMessage();
$ResponseMessage->Status = 'Error';
$ResponseMessage->Message = 'No results';
echo json_encode($ResponseMessage, JSON_UNESCAPED_UNICODE);
exit;
}
$Response = array();
if ($ResponseMessage) {
$Response['Status'] = $ResponseMessage->Status;
$Response['Message'] = $ResponseMessage->Message;
}
$Response['LandContracts'] = array_values($array);
echo json_encode($Response, JSON_UNESCAPED_UNICODE);
$stmt = null;
}
You are better off using a JOIN query, and then structure your array from the result - having a query within a loop is often a very bad idea, and an indicator that you can use a JOIN instead.
You want to use a LEFT JOIN, joining them on the land_contract_id in both tables.
Then loop your results, and construct your array, which you can end up encoding into a JSON string once done.
$params = [];
$array = [];
$sql = "SELECT lc.*,
py.land_contract_annual_price_year AS `year`,
py.land_contract_annual_price_amount AS `amount`
FROM land_contract AS lc
LEFT JOIN land_contract_annual_price AS py
ON py.land_contract_id = lc.land_contract_id
";
if (isset($_POST['land_contract_id'])) {
$sql .= 'WHERE lc.land_contract_id = ?';
$params[] = $_POST["land_contract_id"];
}
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
while ($row = $stmt->fetch()) {
// Fields we want to extract from the select statement into the array
$select_fields = ['land_contract_id', 'land_contract_name', 'location_id', 'land_contract_link', 'land_contract_notes', 'land_owner_id',
'land_contract_start_date', 'land_contract_end_date', 'land_contract_terminated', 'land_contract_payment_interval',
'land_contract_price_type', 'land_contract_fixed_annual_price '];
if (!isset($array[$row['land_contract_id']])) {
// initialize the subarray if it has not been set already
$array[$row['land_contract_id']] = array_intersect_key($row, array_flip($select_fields));
if ($row['year'] != null) {
$array[$row['land_contract_id']]['land_contract_annual_prices'] = [];
} else {
$array[$row['land_contract_id']]['land_contract_annual_price'] = $row['land_contract_fixed_annual_price'];
}
}
if ($row['year'] != null) {
$array[$row['land_contract_id']]['land_contract_annual_prices'][] = ['year' => $row['year'], 'amount' => $row['amount']];
}
}
if (empty($array)) {
echo "No results";
exit;
}
echo json_encode($array, JSON_UNESCAPED_UNICODE);
I can not manage to see all the lines of my mysql query result returned as JSON Object using JSON_encode() php function.
Here is my code :
$Sql_Query = "SELECT * FROM Users";
$result = mysqli_query($dbc,$Sql_Query);
$ligne = array();
$bilan = array();
while ($rowr = mysqli_fetch_assoc($result)) {
$ligne = array (
"User_ID" => $rowr['User_ID']
);
$bilan[$ligne['User']] = $ligne[[
['User_ID'][$rowr['User_ID']]
]];
array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);
It returns me :
{"":null,"0":{"User_ID":"1"},"1":{"User_ID":"19"},"2":{"User_ID":"78"},"3":{"User_ID":"79"},"4":{"User_ID":"85"},"5":{"User_ID":"86"},"6":{"User_ID":"87"},"7":{"User_ID":"88"},"8":{"User_ID":"91"},"9":{"User_ID":"92"},"10":{"User_ID":"93"},"11":{"User_ID":"94"},"12":{"User_ID":"95"},"13":{"User_ID":"96"},"14":{"User_ID":"97"},"15":{"User_ID":"98"},"16":{"User_ID":"99"},"17":{"User_ID":"100"},"18":{"User_ID":"101"},"19":{"User_ID":"102"},"20":{"User_ID":"103"},"21":{"User_ID":"104"},"22":{"User_ID":"105"},"23":{"User_ID":"106"},"24":{"User_ID":"107"},"25":{"User_ID":"108"},"26":{"User_ID":"109"},"27":{"User_ID":"110"},"28":{"User_ID":"111"},"29":{"User_ID":"112"},"30":{"User_ID":"113"},"31":{"User_ID":"114"},"32":{"User_ID":"115"},"33":{"User_ID":"116"}}
Now, I am trying to associate the other fields of each record in the json output. But when adding this to me code, there is no more output.
while ($rowr = mysqli_fetch_assoc($result)) {
$ligne = array (
"User_ID" => $rowr['User_ID'],
"User_Nom" => $rowr['User_Nom']
);
$bilan[$ligne['User']] = $ligne[[
['User_ID'][$rowr['User_ID']]
][
['User_Nom'][$rowr['User_Nom']]
]];
array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);
It seems like on numerical values can be displayed and not alpha characters.
Please help me mixing in the same output both numerical and alpha contents.
Thanks
Arnaud
$ligne['User'] is not initialised, could you try this:
while ($rowr = mysqli_fetch_assoc($result)) {
$ligne = array (
"User_ID" => $rowr['User_ID'],
"User_Nom" => $rowr['User_Nom']
);
array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);
I tested it with this code
$result[] = ['User_ID' => 1, 'User_Nom' => 'Nom1'];
$result[] = ['User_ID' => 2, 'User_Nom' => 'Nom2'];
$result[] = ['User_ID' => 3, 'User_Nom' => 'Nom3'];
$bilan = [];
while ($rowr = array_pop($result)) {
$ligne = array (
"User_ID" => $rowr['User_ID'],
"User_Nom" => $rowr['User_Nom']
);
array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);
It provides this result:
{"0":{"User_ID":3,"User_Nom":"Nom3"},"1":{"User_ID":2,"User_Nom":"Nom2"},"2":{"User_ID":1,"User_Nom":"Nom1"}}
Note the result has a different start, it does not contain
"":null,
any more. This was the result of the strange $bilan[undefined] = undefined line
Converted to PHP >= 5.5 for clarity.
I am guessing and making assumptions, but what else can I do? The main issue I see is that you may be tripping over your feet with the array syntax. It appears that you want to re-index the results by 'User_ID', which I assume is some string identifier found in each table record.
Modularized, in the procedural form ...
/*
Assuming you are attempting to re-index by the 'User_ID' field
of each record before encoding as JSON.
*/
function getDb($ip, $user, $password, $database) {
$db = mysqli_connect($ip, $user, $password, $database);
//error checking etc ...
return $db;
}
function selectRecords(mysqli $db, $sql) {
$result = mysqli_query($db, $sql);
if (!$result) {
throw new UnexpectedValueException("Database query (read) was unsuccessful!");
}
return $result;
}
function getUserRecords(mysqli $db) {
$query = 'SELECT * FROM Users';
return selectRecords($db, $query);
}
function reindexByField($newIndex, $userResults) {
$reindexed = [];
while ($row = mysqli_fetch_assoc($userResults)) {
if (!isset($row[$newInded])) {
throw new OutofBoundsException("The index '" . $newIndex . "' does not exist in the tested record");
}
$redindexed[$row[$newIndex]] = $row;
}
return $reindexed;
}
function getJsonFromArray(array $records) {
$json = json_encode($records, JSON_FORCE_OBJECT);
if (!$json) {
throw new UnexpectedValueException("Records were not encoded into a JSON formatted string. Got boolean false, instead.");
}
return $json;
}
In the procedural form, then ...
try {
$db = getDb($ip, $user, $password, $db); // Just pretend for a moment.
echo getJsonFromArray(reindexByField('User_ID', getUserRecords($db));
} catch (e) {
// Your handler code here.
} finally {
mysqli_close($db);
}
An object-oriented approach can make your code more organized.
You're right, since the orginal clean plan, because it was not working, I made too many modifications which finally added complexity where there is no need...
I found in php doc the possibility to learn more about the error generated when adding the other fields in the json conversion. json_last_error() was the key for understanding the issue.
So I added :
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - Aucune erreur';
break;
case JSON_ERROR_DEPTH:
echo ' - Profondeur maximale atteinte';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Inadéquation des modes ou underflow';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Erreur lors du contrôle des caractères';
break;
case JSON_ERROR_SYNTAX:
echo ' - Erreur de syntaxe ; JSON malformé';
break;
case JSON_ERROR_UTF8:
echo ' - Caractères UTF-8 malformés, probablement une erreur d\'encodage';
break;
default:
echo ' - Erreur inconnue';
break;
}
This returns me a UTF-8 encoding issue. So I modified my code adding some
utf8_encode($rowr['Fieldname'])
First working solution is very near from #PaulH one's, just, in my specific case, I definetely have to add (utf8_encode()) statement :
$Sql_Query = "SELECT * FROM Users";
$result = mysqli_query($dbc,$Sql_Query);
$ligne =array();
$bilan = array();
while ($rowr = mysqli_fetch_assoc($result)) {
$ligne = array ("User_ID" => $rowr['User_ID'],
"User_Nom" => utf8_encode($rowr['User_Nom']),
"User_Prenom" =>utf8_encode($rowr['User_Prenom']));
array_push ($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);
and it now displays all the fields, all the lines. But there were still some "é" transformed to "\u00e9". So this post put the final brick to the solution.
I modified :
JSON_FORCED_OBJECT
to
JSON_UNESCAPED_UNICODE
as json_encode() parameter.
Finally, code delivering exactly what I want is the following :
$Sql_Query = "SELECT * FROM Users";
$result = mysqli_query($dbc,$Sql_Query);
$bilan = array();
while ($rowr = mysqli_fetch_assoc($result)) {
$ligne = array ("User_ID" => $rowr['User_ID'],
"User_Nom" => utf8_encode($rowr['User_Nom']),
"User_Prenom" =>utf8_encode($rowr['User_Prenom']));
array_push ($bilan, $ligne);
}
echo json_encode($bilan, JSON_UNESCAPED_UNICODE);
I have two lists of check boxes. I am checking which check box is selected and based on that I am trying to get an array.
Let's say the two lists are size which have small, medium, large boxes checked and the other one is color which have red, green, blue boxes checked. The array should look something like:
array[['small', 'medium', 'large']['red', 'green', 'blue']]
But I am getting this:
array[["small"],["medium"],["large"]] [["red"],["green"],["blue"]]
This is the code:
$counter = 0;
$attributes_list = [];
foreach($features_cuts_list as $k => $features_cut) {
$inner_counter = 0;
if ($features_cut["selectedid"] != "") {
$attributes_list[$counter] = [];
$title_to_get = $features_cut["features_cuts_id"];
/* Gets the name of the box that is checked */
$query = "SELECT title FROM features_cuts_translations WHERE lang = '$lang' AND features_cuts_id = '$title_to_get' LIMIT 1;";
$result = mysql_query($query) or die("Cannot query");
$attribute_name = mysql_fetch_row($result);
foreach ($attribute_name as $q) {
array_push($attributes_list[$counter], $q);
}
$counter++;
} else {
}
}
EDIT:
This is the deceleration process for $features_cuts_list:
function getListValuesSql($sql){
global $link; //Database connection
$data=array();
$subData{0}=array();
$res=mysql_query($sql,$link);
if(mysql_num_rows($res)>0){
$i=0;
while($row=mysql_fetch_array($res)){
for($j=0;$j<mysql_num_fields($res);$j++){
$field=mysql_field_name($res, $j);
$subData{$i}[$field]=$row[$field];
}
$data[$i]=$subData{$i};
$i++;
}
return $data;
}else{
return 0;
}
}
$feature_id = $feature["features_id"];
$features_cuts_list = $data->getListValuesSql("
SELECT DISTINCT fct.*, fc.sort, fc.inner_id, fc.price,
fcp.features_cuts_id AS selectedid, IFNULL(fcpv.price,fc.price)
AS price, fcpv.sku
FROM `features_cuts` as fc
JOIN `features_cuts_translations` as fct ON fct.features_cuts_id=fc.id
LEFT JOIN `features_cuts_product_values` as fcpv ON fc.id=fcpv.features_cuts_id AND fcpv.product_id='$pageid'
LEFT JOIN `features_cuts_products` as fcp ON fc.id=fcp.features_cuts_id AND fcp.product_id='$pageid'
WHERE fc.features_id='$feature_id' AND fct.lang='$lang'
Order by fc.sort
");
Hopes this is helpful
From reading your code I think you have unnecessarily provided the $counter variable.Try this modified code:
$attributes_list = [];
foreach($features_cuts_list as $k => $features_cut) {
$inner_counter = 0;
if ($features_cut["selectedid"] != "") {
$title_to_get = $features_cut["features_cuts_id"];
/* Gets the name of the box that is checked */
$query = "SELECT title FROM features_cuts_translations WHERE lang = '$lang' AND features_cuts_id = '$title_to_get' LIMIT 1;";
$result = mysql_query($query) or die("Cannot query");
$attribute_name = mysql_fetch_row($result);
foreach ($attribute_name as $q) {
array_push($attributes_list, $q);
}
$counter++;
} else {
}
}
If not completely, it will mostly solve your issue.
Let me know what the result are , after running this piece of code.
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.