php create query string

http_build_query

http_build_query — Generate URL-encoded query string

Description

Generates a URL-encoded query string from the associative (or indexed) array provided.

Parameters

May be an array or object containing properties.

If data is an array, it may be a simple one-dimensional structure, or an array of arrays (which in turn may contain other arrays).

If data is an object, then only public properties will be incorporated into the result.

If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only.

This is meant to allow for legal variable names when the data is decoded by PHP or another CGI application later on.

arg_separator.output is used to separate arguments but may be overridden by specifying this parameter.

Return Values

Returns a URL-encoded string.

Examples

Example #1 Simple usage of http_build_query()

The above example will output:

Example #2 http_build_query() with numerically index elements.

The above example will output:

Example #3 http_build_query() with complex arrays

this will output : (word wrapped for readability)

Only the numerically indexed element in the base array «CEO» received a prefix. The other numeric indices, found under pastimes, do not require a string prefix to be legal variable names.

Example #4 Using http_build_query() with an object

$parent = new parentClass ();

The above example will output:

See Also

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.

Источник

Parse query string into an array

How can I turn a string below into an array?

This is the array I am looking for,

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

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.

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

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:

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

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

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

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

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

There are several possible methods, but for you, there is already a builtin parse_str function

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

This is one-liner for parsing query from current URL into array:

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

You can use the PHP string function parse_str() followed by foreach loop.

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

You can try this code :

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

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

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

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.

Источник

mysqli::query

Описание

Выполняет запрос query к базе данных.

Список параметров

Предупреждение безопасности: SQL-инъекция

Режим результата может быть одной из 3 констант, указывающих, как результат будет возвращён сервером MySQL.

Возвращаемые значения

Примеры

Пример #1 Пример использования mysqli::query()

Результат выполнения данных примеров:

Смотрите также

User Contributed Notes 22 notes

This may or may not be obvious to people but perhaps it will help someone.

When running joins in SQL you may encounter a problem if you are trying to pull two columns with the same name. mysqli returns the last in the query when called by name. So to get what you need you can use an alias.

Below I am trying to join a user id with a user role. in the first table (tbl_usr), role is a number and in the second is a text name (tbl_memrole is a lookup table). If I call them both as role I get the text as it is the last «role» in the query. If I use an alias then I get both as desired as shown below.

= «SELECT a.uid, a.role AS roleid, b.role,
FROM tbl_usr a
INNER JOIN tbl_memrole b
ON a.role = b.id
» ;

?>
In this situation I guess I could have just renamed the role column in the first table roleid and that would have taken care of it, but it was a learning experience.

The cryptic «Couldn’t fetch mysqli» error message can mean any number of things, including:

When calling multiple stored procedures, you can run into the following error: «Commands out of sync; you can’t run this command now».
This can happen even when using the close() function on the result object between calls.
To fix the problem, remember to call the next_result() function on the mysqli object after each stored procedure call. See example below:

// Check for errors
if( mysqli_connect_errno ()) <
echo mysqli_connect_error ();
>

Here is an example of a clean query into a html table

I like to save the query itself in a log file, so that I don’t have to worry about whether the site is live.

For example, I might have a global function:

Translation:
«Couldn’t fetch mysqli»

You closed your connection and are trying to use it again.

It has taken me DAYS to figure out what this obscure error message means.

Use mysqli_query to call a stored procedure that returns a result set.

Here is a short example:

For those using with replication enabled on their servers, add a mysqli_select_db() statement before any data modification queries. MySQL replication does not handle statements with db.table the same and will not replicate to the slaves if a scheme is not selected before.

Building inserts can be annoying. This helper function inserts an array into a table, using the key names as column names:

Calling Stored Procedures

Beeners’ note/example will not work. Use mysqli_multi_query() to call a Stored Procedure. SP’s have a second result-set which contains the status: ‘OK’ or ‘ERR’. Using mysqli_query will not work, as there are multiple results.

mysqli::query() can only execute one SQL statement.

Use mysqli::multi_query() when you want to run multiple SQL statements within one query.

Use difference collation/character for connect, result.
You can set the collation before your query.

E.g. want to set the collation to utf8_general_ci
you can send the query «SET NAMES ‘utf8′» first

Also SET NAMES can repalce with one or some settings like SET character_set_results=’utf8′;

or you could just extend the class.
in my case i already had a wraper for the db so something like this was easy :

public function free($result) <

just tried it and it works like a charm 😉

Recently I had puzzling problem when performing DML queries, update in particular, each time a update query is called and then there are some more queries to follow this error will show on the page and go in the error_log:
«Fatal error: Exception thrown without a stack frame in Unknown on line 0»

The strange thing is that all queries go through just fine so it didn’t make much sense:

So, I don’t know why but it seems that when DML queries are responsible for:
«Fatal error: Exception thrown without a stack frame in Unknown on line 0»
calling «mysqli_free_result» after the query seems to be fixing the issue

Источник

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?

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

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):

Источник

Get URL query string parameters

What is the «less code needed» way to get parameters from a URL query string which is formatted like the following?

Output should be: myqueryhash

I am aware of this approach:

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

11 Answers 11

$_SERVER[‘QUERY_STRING’] contains the data that you are looking for.

DOCUMENTATION

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

The PHP way to do it is using the function parse_url, which parses a URL and return its components. Including the query string.

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

The function parse_str() automatically reads all query parameters into an array.

EDIT

php create query string. Смотреть фото php create query string. Смотреть картинку php create query string. Картинка про php create query string. Фото php create query string

If you want the whole query string:

I will recommended best answer as

The above example will output:

This code and notation is not mine. Evan K solves a multi value same name query with a custom function 😉 is taken from:

It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:

Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.

This can be confusing for anyone who’s used to the CGI standard, so keep it in mind. As an alternative, I use a «proper» querystring parser function:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *