PHP array to postgres array - php

Now php can't work directly wit Postgresql array. For example, php taking postgresql array like
'{"foo","bar"}'
I need simple php function to create multidimensional postgresql array from php array.
I think that experimental pg_convert() isn't optimal because it needs of extra data to form simple array string for database output, maybe I misunderstood the idea of this function.
For example, I need to convert
$from=array( array( "par_1_1","par_1_2" ), array( "array_2_1", "array_2_2" ) );
$to='{{"par_1_1","par_1_2"},{"par_2_1","par_2_2"}}';
Can I use array_walk_recursive() to convert the deepest elements of array?

Here's a simple function for converting a PHP array to PG array.
function to_pg_array($set) {
settype($set, 'array'); // can be called with a scalar or array
$result = array();
foreach ($set as $t) {
if (is_array($t)) {
$result[] = to_pg_array($t);
} else {
$t = str_replace('"', '\\"', $t); // escape double quote
if (! is_numeric($t)) // quote only non-numeric values
$t = '"' . $t . '"';
$result[] = $t;
}
}
return '{' . implode(",", $result) . '}'; // format
}

A little edit that uses pg_escape_string for quoting and that support PHP NULLS and booleans:
/**
* Converts a php array into a postgres array (also multidimensional)
*
* Each element is escaped using pg_escape_string, only string values
* are enclosed within single quotes, numeric values no; special
* elements as php nulls or booleans are literally converted, so the
* php NULL value is written literally 'NULL' and becomes a postgres
* NULL (the same thing is done with TRUE and FALSE values).
*
* Examples :
* VARCHAR VERY BASTARD ARRAY :
* $input = array('bla bla', 'ehi "hello"', 'abc, def', ' \'VERY\' "BASTARD,\'value"', NULL);
*
* to_pg_array($input) ==>> 'ARRAY['bla bla','ehi "hello"','abc, def',' ''VERY'' "BASTARD,''value"',NULL]'
*
* try to put this value in a query (you will get a valid result):
* select unnest(ARRAY['bla bla','ehi "hello"','abc, def',' ''VERY'' "BASTARD,''value"',NULL]::varchar[])
*
* NUMERIC ARRAY:
* $input = array(1, 2, 3, 8.5, null, 7.32);
* to_pg_array($input) ==>> 'ARRAY[1,2,3,8.5,NULL,7.32]'
* try: select unnest(ARRAY[1,2,3,8.5,NULL,7.32]::numeric[])
*
* BOOLEAN ARRAY:
* $input = array(false, true, true, null);
* to_pg_array($input) ==>> 'ARRAY[FALSE,TRUE,TRUE,NULL]'
* try: select unnest(ARRAY[FALSE,TRUE,TRUE,NULL]::boolean[])
*
* MULTIDIMENSIONAL ARRAY:
* $input = array(array('abc', 'def'), array('ghi', 'jkl'));
* to_pg_array($input) ==>> 'ARRAY[ARRAY['abc','def'],ARRAY['ghi','jkl']]'
* try: select ARRAY[ARRAY['abc','def'],ARRAY['ghi','jkl']]::varchar[][]
*
* EMPTY ARRAY (is different than null!!!):
* $input = array();
* to_pg_array($input) ==>> 'ARRAY[]'
* try: select unnest(ARRAY[]::varchar[])
*
* NULL VALUE :
* $input = NULL;
* to_pg_array($input) ==>> 'NULL'
* the functions returns a string='NULL' (literally 'NULL'), so putting it
* in the query, it becomes a postgres null value.
*
* If you pass a value that is not an array, the function returns a literal 'NULL'.
*
* You should put the result of this functions directly inside a query,
* without quoting or escaping it and you cannot use this result as parameter
* of a prepared statement.
*
* Example:
* $q = 'INSERT INTO foo (field1, field_array) VALUES ($1, ' . to_pg_array($php_array) . '::varchar[])';
* $params = array('scalar_parameter');
*
* It is recommended to write the array type (ex. varchar[], numeric[], ...)
* because if the array is empty or contains only null values, postgres
* can give an error (cannot determine type of an empty array...)
*
* The function returns only a syntactically well-formed array, it does not
* make any logical check, you should consider that postgres gives errors
* if you mix different types (ex. numeric and text) or different dimensions
* in a multidim array.
*
* #param array $set PHP array
*
* #return string Array in postgres syntax
*/
function to_pg_array($set) {
if (is_null($set) || !is_array($set)) {
return 'NULL';
}
// can be called with a scalar or array
settype($set, 'array');
$result = array();
foreach ($set as $t) {
// Element is array : recursion
if (is_array($t)) {
$result[] = to_pg_array($t);
}
else {
// PHP NULL
if (is_null($t)) {
$result[] = 'NULL';
}
// PHP TRUE::boolean
elseif (is_bool($t) && $t == TRUE) {
$result[] = 'TRUE';
}
// PHP FALSE::boolean
elseif (is_bool($t) && $t == FALSE) {
$result[] = 'FALSE';
}
// Other scalar value
else {
// Escape
$t = pg_escape_string($t);
// quote only non-numeric values
if (!is_numeric($t)) {
$t = '\'' . $t . '\'';
}
$result[] = $t;
}
}
}
return 'ARRAY[' . implode(",", $result) . ']'; // format
}

This is the same as mstefano80's answer, but more human-readable, universal and modern (at least for me):
<?php
class Sql
{
/**
* Convert PHP-array to SQL-array
* https://stackoverflow.com/questions/5631387/php-array-to-postgres-array
*
* #param array $data
* #return string
*/
public static function toArray(array $data, $escape = 'pg_escape_string')
{
$result = [];
foreach ($data as $element) {
if (is_array($element)) {
$result[] = static::toArray($element, $escape);
} elseif ($element === null) {
$result[] = 'NULL';
} elseif ($element === true) {
$result[] = 'TRUE';
} elseif ($element === false) {
$result[] = 'FALSE';
} elseif (is_numeric($element)) {
$result[] = $element;
} elseif (is_string($element)) {
$result[] = "'" . $escape($element) . "'";
} else {
throw new \InvalidArgumentException("Unsupported array item");
}
}
return sprintf('ARRAY[%s]', implode(',', $result));
}
}
Tests:
<?php
use Sql;
class SqlTest extends \PHPUnit_Framework_TestCase
{
public function testToArray()
{
$this->assertSame("ARRAY['foo','bar']", Sql::toArray(['foo', 'bar']));
$this->assertSame("ARRAY[1,2]", Sql::toArray([1, 2]));
$this->assertSame("ARRAY[1,2]", Sql::toArray(['1', '2']));
$this->assertSame("ARRAY['foo\\\"bar','bar\'foo']", Sql::toArray(['foo"bar', 'bar\'foo'], function($str){
return addslashes($str);
}));
$this->assertSame("ARRAY[ARRAY['foo\\\"bar'],ARRAY['bar\'foo']]", Sql::toArray([['foo"bar'], ['bar\'foo']], function($str){
return addslashes($str);
}));
}
}

Related

$$ array variable in PHP [duplicate]

This question already has answers here:
Access array using dynamic path
(3 answers)
Closed 7 years ago.
I can use $$ variables to refer variable like this
$var = 'car';
$car = 'Lamborghini';
echo $$var;
Above code will echo Lamborghini.
However I am having a code like this:-
$var = "['acct_1']['etc']['anotherInfo']['sing']";
$var = 'arr'.$var;
echo $arr['acct_1']['etc']['anotherInfo']['sing'] ;
echo $$var;
First echo prints the correct value but $$var doesn't give the correct value.
Any help is much appreciated.
Thanks
You can always keep the keys in an array, and then iterate on them to resolve the value correctly:
$keys = ['acct_1', 'etc', 'anotherInfo', 'sing'];
$val = $arr;
foreach($keys as $key) {
$val = $val[$key];
}
Now, both $arr['acct_1']['etc']['anotherInfo']['sing'] and $val have the same value.
Try it in this demo.
Edit:
You already have the $keys array in $indexInfo. You should be able to use it like so:
function replaceValue($arr, $indexInfo, $char)
{
// $indexInfo is all you need!
$var = $arr;
foreach($indexInfo as $key) {
$var = $var[$key];
}
echo $arr['acct_1']['etc']['anotherInfo']['sing'] . "\n";
echo $var . "\n";
die($var);
}
That won't work unfortunately, however why not do something line this
/**
* Search into a multi dimensional array to find arbitrary data
* #param array $array The array to search
* #param string ... Any number of array keys
* #return mixed
*/
function deepArraySearch(array $array) {
$keys = func_get_args();
array_shift($keys); // First element is the array
// If no more keys to use
if(!$keys) {
return $array;
}
$nextKey = array_shift($keys);
$nextData = $array[$nextKey];
// Nothing left to search
if(!is_array($nextData )) {
return $nextData ;
}
array_unshift($keys, $nextData);
return call_user_func_array('deepArraySearch', $keys);
}
$arr = ['one' => ['two' => ['three' => 'data']]];
print_r(deepArraySearch($arr, 'one'));
print_r(deepArraySearch($arr, 'one', 'two'));
print_r(deepArraySearch($arr, 'one', 'two', 'three'));
echo PHP_EOL;
In your case I guess it would work like this
$arr = ['acct_1' => ['etc' => ['anotherInfo' => ['sing' => 'song']]]];
print_r(deepArraySearch($arr, 'acct_1', 'etc', 'anotherInfo', 'sing')); // song
Final note:
If you're using PHP 5.6, 7, or HHVM, this function is way nicer:
<?php
/**
* Search into a multi dimensional array to find arbitrary data
* #param array $array The array to search
* #param string ... Any number of array keys
* #return mixed
*/
function deepArraySearch(array $array, ...$keys) {
// If no more keys to use
if(!$keys) {
return $array;
}
$nextKey = array_shift($keys);
$nextData = $array[$nextKey];
// Nothing left to search
if(!is_array($nextData )) {
return $nextData ;
}
return deepArraySearch($nextData, ...$keys);
}
Demo: http://3v4l.org/vmocO

Accessing Multidimensional Array Values without recursive functions and/or loops

I have index ponter, for example 5-1-key2-3.
And my array has its address:
array(
'5'=>array(
'1'=>array(
'key2'=>array(
'3'=>'here it is - 5-1-key2-3 key address'
)
)
)
)
which equals to
$arr[5][1][key2][3]='here it is - 5-1-key2-3 key address';
I know I can build the recursive function to access this value.
But I'm curious is it possible to achieve this without recursion and building user's functions and/or loops.
Probably it can be done with variable variables feature in php.
You can use this code
$keys = explode('-', '5-1-key2-3');
// start from the root of the array and progress through the elements
$temp = $arr;
foreach ($keys as $key_value)
{
$temp = $temp[$key_value];
}
// this will give you $arr["5"]["1"]["key2"]["3"] element value
echo $temp;
modifications after I got better understanding of the question I think you can do it with eval:
<?php
function getArrValuesFromString($string, $arr) {
$stringArr = '$arr[\'' . str_replace('-', "']['", $string) . '\']';
eval("\$t = " . $stringArr . ";");
return $t;
}
$arr[5][1]['key2'][3] = '1here it is - 5-1-key2-3 key address';
$string = '5-1-key2-3';
echo getArrValuesFromString($string, $arr); //1here it is - 5-1-key2-3 key address
EDIT :
Here is a way I deprecate so much, because of security, but if you are sure of what you are doing :
$key = 'a-b-c-d';
$array = <<your array>>;
$keys = explode('-', $key);
// we can surely do something better like checking for each one if its a string or int then adding or not the `'`
$final_key = "['".implode("']['", $keys)."']";
$result = eval("return \$array{$final_key};");
There is a class I wrote inspired from something I read on the web don't really remember where but anyway, this can helps you :
/**
* Class MultidimensionalHelper
*
* Some help about multidimensional arrays
* like dynamic array_key_exists, set, and get functions
*
* #package Core\Utils\Arrays
*/
class MultidimensionalHelper
{
protected $keySeparator = '.';
/**
* #return string
*/
public function keySeparator()
{
return $this->keySeparator;
}
/**
* #param string $keySeparator
*/
public function setKeySeparator($keySeparator)
{
$this->keySeparator = $keySeparator;
}
/**
* Multidimensional array dynamic array_key_exists
*
* #param $key String Needle
* #param $array Array Haystack
* #return bool True if found, false either
*/
public function exists($key, $array)
{
$keys = explode($this->keySeparator(), $key);
$tmp = $array;
foreach($keys as $k)
{
if(!array_key_exists($k, $tmp))
{
return false;
}
$tmp = $tmp[$k];
}
return true;
}
/**
* Multidimensional array dynamic getter
*
*
* #param $key String Needle
* #param $array Array Haystack
* #return mixed Null if key not exists or the content of the key
*/
public function get($key, $array)
{
$keys = explode($this->keySeparator(), $key);
$lkey = array_pop($keys);
$tmp = $array;
foreach($keys as $k)
{
if(!isset($tmp[$k]))
{
return null;
}
$tmp = $tmp[$k];
}
return $tmp[$lkey];
}
/**
* Multidimensional array dynamic setter
*
* #param String $key
* #param Mixed $value
* #param Array $array Array to modify
* #param Bool $return
* #return Array If $return is set to TRUE (bool), this function
* returns the modified array instead of directly modifying it.
*/
public function set($key, $value, &$array)
{
$keys = explode($this->keySeparator(), $key);
$lkey = array_pop($keys);
$tmp = &$array;
foreach($keys as $k)
{
if(!isset($tmp[$k]) || !is_array($tmp[$k]))
{
$tmp[$k] = array();
}
$tmp = &$tmp[$k];
}
$tmp[$lkey] = $value;
unset($tmp);
}
}
Then use :
$MDH = new MultidimensionalHelper();
$MDH->setKeySeparator('-');
$arr = [
'a' => [
'b' => [
'c' => 'good value',
],
'c' => 'wrong value',
],
'b' => [
'c' => 'wrong value',
]
];
$key = 'a-b-c';
$val = $MDH->get($key, $arr);
var_dump($val);
Here is the content of the get function if you don't find it in Class code :
public function get($key, $array)
{
$keys = explode($this->keySeparator(), $key);
$lkey = array_pop($keys);
$tmp = $array;
foreach($keys as $k)
{
if(!isset($tmp[$k]))
{
return null;
}
$tmp = $tmp[$k];
}
return $tmp[$lkey];
}

How to Convert 2D array into 1D array?

I want to convert my 2D array into 1D array.
When I do var_dump($image_name_db);
It shows :
array(2) {
[0]=>
array(1) {
["image"]=>
string(7) "pic.PNG"
}
[1]=>
array(1) {
["image"]=>
string(14) "abouttown3.jpg"
}
}
Now how can I convert It into 1D array. As I want to compare two arrays. One array is 1D and other array is 2D, that is why i want 2D array in 1D. So i need both of them in 1D to compare easily.
I am using codeigniter.
Use array_column() function for it, if php version is 5.5+
array_column($image_name_db, 'image');
See: http://php.net/manual/en/function.array-column.php
For below unsupported version use https://github.com/ramsey/array_column
if (!function_exists('array_column')) {
/**
* Returns the values from a single column of the input array, identified by
* the $columnKey.
*
* Optionally, you may provide an $indexKey to index the values in the returned
* array by the values from the $indexKey column in the input array.
*
* #param array $input A multi-dimensional array (record set) from which to pull
* a column of values.
* #param mixed $columnKey The column of values to return. This value may be the
* integer key of the column you wish to retrieve, or it
* may be the string key name for an associative array.
* #param mixed $indexKey (Optional.) The column to use as the index/keys for
* the returned array. This value may be the integer key
* of the column, or it may be the string key name.
* #return array
*/
function array_column($input = null, $columnKey = null, $indexKey = null)
{
// Using func_get_args() in order to check for proper number of
// parameters and trigger errors exactly as the built-in array_column()
// does in PHP 5.5.
$argc = func_num_args();
$params = func_get_args();
if ($argc < 2) {
trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);
return null;
}
if (!is_array($params[0])) {
trigger_error(
'array_column() expects parameter 1 to be array, ' . gettype($params[0]) . ' given',
E_USER_WARNING
);
return null;
}
if (!is_int($params[1])
&& !is_float($params[1])
&& !is_string($params[1])
&& $params[1] !== null
&& !(is_object($params[1]) && method_exists($params[1], '__toString'))
) {
trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING);
return false;
}
if (isset($params[2])
&& !is_int($params[2])
&& !is_float($params[2])
&& !is_string($params[2])
&& !(is_object($params[2]) && method_exists($params[2], '__toString'))
) {
trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING);
return false;
}
$paramsInput = $params[0];
$paramsColumnKey = ($params[1] !== null) ? (string) $params[1] : null;
$paramsIndexKey = null;
if (isset($params[2])) {
if (is_float($params[2]) || is_int($params[2])) {
$paramsIndexKey = (int) $params[2];
} else {
$paramsIndexKey = (string) $params[2];
}
}
$resultArray = array();
foreach ($paramsInput as $row) {
$key = $value = null;
$keySet = $valueSet = false;
if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
$keySet = true;
$key = (string) $row[$paramsIndexKey];
}
if ($paramsColumnKey === null) {
$valueSet = true;
$value = $row;
} elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
$valueSet = true;
$value = $row[$paramsColumnKey];
}
if ($valueSet) {
if ($keySet) {
$resultArray[$key] = $value;
} else {
$resultArray[] = $value;
}
}
}
return $resultArray;
}
}
or use array_map
$image_name_arr = array_map(function($arr){
return $arr['image'];
},$image_name_db);
You need to traverse through the array and store images in to a 1D array.
<?php
$arr = array();
$arr[0]['image'] = 'pic.PNG';
$arr[1]['image'] = 'abouttown3.jpg';
$images = array();
if (! empty($arr)) {
foreach ($arr as $row) {
$images[] = $row['image'];
}
}
echo "<br/> Existing";
echo '<pre>';
print_r($arr);
echo '</pre>';
echo "<br/> New";
echo '<pre>';
print_r($images);
echo '</pre>';
Working demo:
Try with -
$array = array(array("image" => "pic.PNG"), array("image" => "abouttown3.jpg"));
$new = array_map(function($arr) {
return $arr['image'];
}, $array);
OutPut
array(2) {
[0]=>
string(7) "pic.PNG"
[1]=>
string(14) "abouttown3.jpg"
}
The best way is to use array_map, according to php doc:
array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()
example :
$output = array_map(function($current){
return $current['image'];
},$your_array);
explanations :
The callback function receive the current element ($current) in the iterated array ($your_array, the 2D array) and returns the value to push to a new array (the output array is $output, it is a 1D array).
Why create a new problem when your original problem "How to compare two multidimensional arrays" can be solved easily?
Check out Compare multidimensional arrays in PHP for more input.
If you really want to convert a multidimensional array into a single dimension, check out this post: How to convert two dimensional array to one dimensional array in php5

Prevent quoting of certain values with PHP json_encode()

When using PHP's json_encode to encode an array as a JSON string, is there any way at all to prevent the function from quoting specific values in the returned string? The reason I ask is because I need javascript to interpret certain values in the object as actual variable names, for example the name of an existing javascript function.
My end goal is to use the outputted json as the configuration object for an ExtJS Menu component, so the fact that everything gets quoted prevents me from successfully setting such properties as "handler" (click event handler function) of the child items arrays.
What we do is (and that's what Zend_Json::encode() does too), is to use a special marker class that encapsulates Javascript expressions in a special class. The encoding then walks recursively through our array-to-be-encoded, replaces all marker instances with some string. After using the built-in json_encode() we simply do a string replace to replace each special string with the __toString() value of the respective marker instance.
You can either use Zend_Json directly (if that's possible) or check how they do it and adapt the code to your needs.
Bill's function almost worked, it just needed the is_assoc() function added.
But while I was sorting this out, I cleaned it up a bit. This seems to work quite well for me:
<?php
/**
* JSObject class.
*/
class JSObject {
var $jsexp = 'JSEXP:';
/**
* is_assoc function.
*
* Determines whether or not the object is an associative array
*
* #access public
* #param mixed $arr
* #return boolean
*/
function is_assoc($arr) {
return (is_array($arr) && count(array_filter(array_keys($arr),'is_string')) == count($arr));
}
/**
* Encode object
*
* Encodes the object as a json string, parsing out items that were flagged as objects so that they are not wrapped in double quotes.
*
* #param array $properties
* #return string
*/
function encode($properties = array()) {
$is_assoc = $this->is_assoc($properties);
$enc_left = $is_assoc ? '{' : '[';
$enc_right = $is_assoc ? '}' : ']';
$outputArray = array();
foreach ($properties as $prop => $value) {
if ((is_array($value) && !empty($value)) || (is_string($value) && strlen(trim(str_replace($this->jsexp, '', $value))) > 0) || is_int($value) || is_float($value) || is_bool($value)) {
$output = (is_string($prop)) ? $prop.': ' : '';
if (is_array($value)) {
$output .= $this->encode($value);
}
else if (is_string($value)) {
$output .= (substr($value, 0, strlen($this->jsexp)) == $this->jsexp) ? substr($value, strlen($this->jsexp)) : json_encode($value);
}
else {
$output .= json_encode($value);
}
$outputArray[] = $output;
}
}
$fullOutput = implode(', ', $outputArray);
return $enc_left . $fullOutput . $enc_right;
}
/**
* JS expression
*
* Prefixes a string with the JS expression flag
* Strings with this flag will not be quoted by encode() so they are evaluated as expressions
*
* #param string $str
* #return string
*/
function js($str) {
return $this->jsexp.$str;
}
}
No, json_encode can't do that. You need to construct your JS expression by hand then:
$json = "{'special':" . json_encode($string) . " + js_var,"
. "'value': 123}";
(Try to still use json_encode for fixed value parts, like in above example.)
The json_encode function does not provide any functionality for controlling the quotes. The quotes are also necessary for JavaScript to properly form the object on the JavaScript side.
In order to use the returned value to construct an object on the JavaScript side, use the json_encoded string to set flags in your association.
For example:
json_encode( array( "click_handler"=> "FOO" ) );
JavaScript side in the AJAX:
if( json.click_handler == "FOO" ) {
json.click_handler = Your_Handler;
}
After these steps you can pass your object off somewhere.
my quickfix was this:
$myobject->withquotes = 'mystring';
$myobject->withoutquotes = '##noquote## mystring ##noquote##';
and later
str_replace(array('"##noquote## ', ' ##noquote##"'), '', json_encode($myobject))
result is something like this
{"withquotes":"mystring","withoutquotes":mystring}
This is what I ended up doing, which is pretty close to what Stefan suggested above I think:
class JSObject
{
var $jsexp = 'JSEXP:';
/**
* Encode object
*
*
* #param array $properties
* #return string
*/
function encode($properties=array())
{
$output = '';
$enc_left = $this->is_assoc($properties) ? '{' : '[';
$enc_right = ($enc_left == '{') ? '}' : ']';
foreach($properties as $prop => $value)
{
//map 'true' and 'false' string values to their boolean equivalent
if($value === 'true') { $value = true; }
if($value === 'false') { $value = false; }
if((is_array($value) && !empty($value)) || (is_string($value) && strlen(trim(str_replace($this->jsexp, '', $value))) > 0) || is_int($value) || is_float($value) || is_bool($value))
{
$output .= (is_string($prop)) ? $prop.': ' : '';
if(is_array($value))
{
$output .= $this->encode($value);
}
else if(is_string($value))
{
$output .= (substr($value, 0, strlen($this->jsexp)) == $this->jsexp) ? substr($value, strlen($this->jsexp)) : '\''.$value.'\'';
}
else if(is_bool($value))
{
$output .= ($value ? 'true' : 'false');
}
else
{
$output .= $value;
}
$output .= ',';
}
}
$output = rtrim($output, ',');
return $enc_left.$output.$enc_right;
}
/**
* JS expression
*
* Prefixes a string with the JS expression flag
* Strings with this flag will not be quoted by encode() so they are evaluated as expressions
*
* #param string $str
* #return string
*/
function js($str)
{
return $this->jsexp.$str;
}
}
Following the lead of Stefan Gehrig I put this rough little class together. Example below. One must remember to use the serialize method if one has used the mark method, otherwise the markers will persist in the final json.
class json_extended {
public static function mark_for_preservation($str) {
return 'OINK' . $str . 'OINK'; // now the oinks will be next to the double quotes
}
public static function serialize($stuff) {
$json = json_encode($stuff);
$json = str_replace(array('"OINK', 'OINK"'), '', $json);
return $json;
}
}
$js_arguments['submitHandler'] = json_extended::mark_for_preservation('handle_submit');
<script>
$("form").validate(<?=json_extended::serialize($js_arguments)?>);
// produces: $("form").validate({"submitHandler":handle_submit});
function handle_submit() {alert( 'Yay, pigs!'); }
</script>

Zend_Db_Select where() and Zend_Db_Adapter quoteInto()

Are Zend_Db_Select's where() method, when including the optional value to quite into, and Zend_Db_Adapte's quoteInto() methods basically the same as far as escaping SQL?
In other words, are these two pieces of quote identical and equally secure?
$select->where($this->getAdapter()->quoteInto('id = ?', 3));
$select->where(id = ?, 3);
Thanks!
Zend_Db_Select::_where() is using Zend_Db_Abstract::quoteInto() to quote the value(s) you specify as the second parameter in Zend_Db_Select::where() when assembling the sql string.
From line 983 of Zend_Db_Select:
/**
* Internal function for creating the where clause
*
* #param string $condition
* #param mixed $value optional
* #param string $type optional
* #param boolean $bool true = AND, false = OR
* #return string clause
*/
protected function _where($condition, $value = null, $type = null, $bool = true)
{
if (count($this->_parts[self::UNION])) {
require_once 'Zend/Db/Select/Exception.php';
throw new Zend_Db_Select_Exception("Invalid use of where clause with " . self::SQL_UNION);
}
if ($value !== null) {
$condition = $this->_adapter->quoteInto($condition, $value, $type);
}
$cond = "";
if ($this->_parts[self::WHERE]) {
if ($bool === true) {
$cond = self::SQL_AND . ' ';
} else {
$cond = self::SQL_OR . ' ';
}
}
return $cond . "($condition)";
}
As I understand it where does this already so specifying it would be redundant.

Categories