php array to get params
http_build_query
http_build_query — Генерирует URL-кодированную строку запроса
Описание
Генерирует URL-кодированную строку запроса из предоставленного ассоциативного (или индексированного) массива.
Список параметров
Может быть массив или объект, содержащий свойства.
Если data массив, то он может быть простой одномерной структурой или массивом массивов (который, в свою очередь, может содержать другие массивы).
Если data объект, тогда только общедоступные свойства будут включены в результат.
Если числовые индексы используются в базовом массиве и этот параметр указан, то он будет добавлен к числовому индексу для элементов только в базовом массиве.
Это позволяет обеспечить допустимые имена переменных, в которые позже данные будут декодированы PHP или другим CGI-приложением.
arg_separator.output используется в качестве разделителя аргументов, но может быть переопределён путём указания этого параметра.
Возвращаемые значения
Возвращает URL-кодированную строку.
Примеры
Пример #1 Простой пример использования http_build_query()
Результат выполнения данного примера:
Пример #2 Пример использования http_build_query() с числовыми индексами элементов.
Результат выполнения данного примера:
Пример #3 Пример использования http_build_query() с многомерными массивами
Результат выполнения данных примеров: (символы перенесены для удобства чтения)
Только числовой индексированный элемент «CEO» в базовом массиве получил префикс. Другие числовые индексы, найденные в pastimes, не требуют строкового префикса, чтобы быть допустимыми именами переменных.
Пример #4 Пример использования http_build_query() с объектом
$parent = new parentClass ();
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 24 notes
Params with null value do not present in result string.
If you need to change the enc_type, use this:
http_build_query($query, null, ini_get(‘arg_separator.output’), PHP_QUERY_RFC3986);
// BAD CODE!
http_build_query($query, null, null, PHP_QUERY_RFC3986);
if you send boolean values it transform in integer :
$a = [teste1= true,teste2=false];
echo http_build_query($a)
//result will be teste1=1&teste2=0
This function makes like this
To do it like this:
As noted before, with php5.3 the separator is & on some servers it seems. Normally if posting to another php5.3 machine this will not be a problem.
But if you post to a tomcat java server or something else the & might not be handled properly.
To overcome this specify:
http_build_query($array); //gives & to some servers
It’s not mentioned in the documentation, but when calling http_build_query on an object, public null fields are ignored.
Is it worth noting that if query_data is an associative array and a value is itself an empty array, or an array of nothing but empty array (or arrays containing only empty arrays etc.), the corresponding key will not appear in the resulting query string?
E.g.
$post_data = array(‘name’=>’miller’, ‘address’=>array(‘address_lines’=>array()), ‘age’=>23);
echo http_build_query($post_data);
Instead you can make your own simple function if you simply want to pass along the data:
If you need the inverse functionality, and (like me) you cannot use pecl_http, you may want to use something akin to the following.
pg_query_params
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
pg_query_params — Посылает параметризованный запрос на сервер, параметры передаются отдельно от текста SQL запроса
Описание
Посылает параметризованный запрос на сервер и ждёт результат. Параметры передаются отдельно от строки запроса.
Список параметров
Пользовательские данные всегда должны передаваться как параметры, и не передаваться в строку запроса напрямую, где они могут привести к возможным атакам через SQL-инъекции и приводит к ошибкам, если данные содержат кавычки. Если по каким-то причинам вы не можете использовать параметр, убедитесь, что пользовательские данные правильно экранированы.
Значения предназначенные для bytea полей нельзя передавать в параметрах. Используйте функцию pg_escape_bytea() или функции для больших объектов.
Возвращаемые значения
Ресурс результата запроса или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования pg_query_params()
// Подключение к базе данных «mary»
$dbconn = pg_connect ( «dbname=mary» );
Смотрите также
User Contributed Notes 15 notes
You can’t run multiple statements with pg_query_params, but you can still have transaction support without falling back to pg_query:
Debugging parameterised queries can be tedious, if you want to paste the query directly into PSQL. Here is a trick that helps:
pg_query and pg_query_params can be combined into a single function. This also removes the need to construct a parameter array for pg_query_params:
If you need to provide multiple possible values for a field in a select query, then the following will help.
The last method works by creating a SQL array containing the desired values. ‘IN (. )’ and ‘ = ANY (. )’ are equivalent, but ANY is for working with arrays, and IN is for working with simple lists.
It is also safe to write your paramerized query in double-quotes, which allows you to mix constant values and placeholders in your query without having to worry about how whether PHP will attempt to substitute any variables in your parameterized string.
A note on type-juggling of booleans:
pg_query_params() and friends do seamless, automatic conversion between PHP-NULL and SQL-NULL and back again, where appropriate.
Hoever, everything else goes in (and comes out) as a string.
The following approach may be helpful when handling boolean fields:
//$row[] now contains booleans, NULLS, and strings.
?>
Note that due to your locale’s number formatting settings, you may not be able to pass a numeric value in as a parameter and have it arrive in PostgreSQL still a number.
If your system locale uses «,» as a decimal separator, the following will result in a database error:
For this to work, it’s necessary to manually convert 3.5 to a string using e.g. number_format.
(I filed this as bug #46408, but apparently it’s expected behavior.)
When inserting into a pg column of type bool, you cannot supply a PHP type of bool. You must instead use a string «t» or «f». PHP attempts to change boolean values supplied as parameters to strings, and then attempts to use a blank string for false.
Example of Failure:
pg_query_params(‘insert into table1 (bool_column) values ($1)’, array(false));
If one of the parameters is an array, (eg. array of ints being passed to a stored procedure), it must be denoted as a set within the array, not php array notation.
eg: var_dump output of 2 parms an integer and array of int
aaa is: Array
(
[0] => 1
[1] => <2,3>
)
How to getParams type of array
In Magento, as usually we used to get param
we can get the param by
6 Answers 6
If you mean get all of the parameters as an array (might be a varien object):
I am afraid it is currently not possible for Zend Framework or Magento to pass array param to zend url.
you can also use brackets on your query params, like http://magento.com/customer/account/view/?id[]=123&id[]=456
My suggestion if you want inputs from visitor as array then instead of passing them in URL as GET params pass those as POST variable.
With Zend Framework 1.12 this is possible with just the method getParam(). Notice the result of getParam() is NULL for no available key, a string for 1 key, and an array for multiple keys:
No ‘id’ value
Single ‘id’ value
Multiple ‘id’ values:
This could be problematic if you always expect a string in your code, and for some reason more values are set in the url: In some cases you can for example run into the error «Array to string conversion«. Here are some tricks to avoid such errors, to make sure you always get the type of result you need from getParam():
Same as above in one line (no NULL, always array):
Maybe there are shorter/better ways to fix these ‘response-types’ of getParam, but if you are going to use the above scripts, it could be cleaner to create another method for it (extended helper or something).
Parse query string into an array
How can I turn a string below into an array?
This is the array I am looking for,
11 Answers 11
You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
Sometimes parse_str() alone is note accurate, it could display for example:
parse_str() would return:
It would be better to combine parse_str() with parse_url() like so:
If you’re having a problem converting a query string to an array because of encoded ampersands
then be sure to use html_entity_decode
Attention, it’s usage is:
Please note that the above only applies to PHP version 5.3 and earlier. Call-time pass-by-reference has been removed in PHP 5.4
There are several possible methods, but for you, there is already a builtin parse_str function
This is one-liner for parsing query from current URL into array:
You can use the PHP string function parse_str() followed by foreach loop.
You can try this code :
This is the PHP code to split query in mysql & mssql
Query before
select xx from xx select xx,(select xx) from xx where y=’ cc’ select xx from xx left join ( select xx) where (select top 1 xxx from xxx) oder by xxx desc «;
Query after
select xx,(select xx) from xx where y=’ cc’
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc
Thank you, from Indonesia Sentrapedagang.com
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra «e»—in the URL the function will silently fail without an error or exception being thrown:
So I prefer using my own parser like so:
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
How to pass an array within a query string?
Is there a standard way of passing an array through a query string?
To be clear, I have a query string with multiple values, one of which would be an array value. I want that query string value to be treated as an array- I don’t want the array to be exploded so that it is indistinguishable from the other query string variables.
Also, according to this post answer, the author suggests that query string support for arrays is not defined. Is this accurate?
EDIT:
Based on @Alex’s answer, there is no standard way of doing this, so my follow-up is then what is an easy way to recognize that the parameter I’m reading is an array in both PHP and Javascript?
Would it be acceptable to name multiple params the same name, and that way I would know that they belong to an array? Example:
Or would this be a bad practice?
11 Answers 11
Here’s what I figured out:
Submitting multi-value form fields, i.e. submitting arrays through GET/POST vars, can be done several different ways, as a standard is not necessarily spelled out.
Three possible ways to send multi-value fields or arrays would be:
Form Examples
On a form, multi-valued fields could take the form of a select box set to multiple:
. or as multiple hidden fields with the same name:
UPDATE
As commenters have pointed out, this is very much framework-specific. Some examples:
Query string:
Rails:
Angular:
See comments for examples in node.js, WordPress, ASP.net
Maintaining order: One more thing to consider is that if you need to maintain the order of your items (i.e. array as an ordered list), you really only have one option, which is passing a delimited list of values, and explicitly converting it to an array yourself.
A query string carries textual data so there is no option but to explode the array, encode it correctly and pass it in a representational format of your choice:
p1=value1&pN=valueN.
data=[value1. valueN]
data=
and then decode it in your server side code.
I don’t think there’s a standard.
Each web environment provides its own ‘standard’ for such things. Besides, the url is usually too short for anything (256 bytes limit on some browsers). Of course longer arrays/data can be send with POST requests.
However, there are some methods:
Although the «square brackets method» is simple and works, it is limited to PHP and arrays.
If other types of variable such as classes or passing variables within query strings in a language other than PHP is required, the JSON method is recommended.
Example in PHP of JSON method (method 2):