Php mysqli multi query

PHP mysqli: multi_query() function

mysqli_multi_query() function / mysqli::multi_query

The mysqli_multi_query() function / mysqli::multi_query performs one or more queries against the database. The queries are separated with a semicolon.

Syntax:

Object oriented style

Procedural style

Parameter:

NameDescriptionRequired / Optional
linkA link identifier returned by mysqli_connect() or mysqli_init()Required for procedural style only and Optional for Object oriented style
queryThe query, as a string.
Data inside the query should be properly escaped.
Required for procedural style only and Optional for Object oriented style

Usage: Procedural style

Parameter:

NameDescriptionRequired/Optional
connectionSpecifies the MySQL connection to useRequired
querySpecifies one or more queries, seperated with semicolonRequired

Return value:

Returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.

Version: PHP 5, PHP 7

Example of object oriented style:

Example of procedural style:

See also

Previous: more_results
Next: next_result

PHP: Tips of the Day

PHP: Showing all errors and warnings

Display errors could be turned off in the php.ini or your Apache configuration file.

You can turn it on in the script:

You should see the same messages in the PHP error log.

Источник

Mysqli query performance multi-query

I was just hoping someone could help me speed up 4 queries with a multi query.

GOAL: a single multi query to function as the single queries below.

Simple queries, i am checking one table to see if user is banned, then if not, i am getting row for the id and updating it’s view count by 1. If user is banned, i do not want the last to queries to complete.

Thank you in advance for your help.

current performance is around 1200ms. (+1000ms avg for facebook graph api query).

NOTE: af_freefeed.pageid & af_ban.pageid are both indexed in database.

ALSO: I have been studying and referencing from http://www.php.net/manual/en/mysqli.multi-query.php i just can not see how to get this config into multi with the if()

actual request times.

Multi_query #1 How to stop the multi query if user is banned?

Possible Contender: 943.8181ms. if added : 933.1279ms. if banned

10ms difference if exit loop for banned. This leads me to believe the loop is completing all the queries before they are actually supposed to be executed, «next_result». Or i have an error in how i looped the functions.

Multi_query #2 «current for benchmark» How to remove duplicate fields in result set after next_result()?

5 Answers 5

Update

You can also try this link for further explanation

EDIT : So now, the conclusion: (test case below)

You cannot control the execution of subsequent statements of a multi-statement query.
You can therefore not use multi_query() in the way you wanted to.

Execute them all, or execute none.

Regarding
Multi_query #2 «current for benchmark» How to remove duplicate fields in result set after next_result()?

About multi_query():

I recently worked on a program using the MySQL C API, which mysqli uses, too.
About multiple-statement query support the documentation states:

Executing a multiple-statement string can produce multiple result sets or row-count indicators. Processing these results involves a different approach than for the single-statement case: After handling the result from the first statement, it is necessary to check whether more results exist and process them in turn if so. To support multiple-result processing, the C API includes the mysql_more_results() and mysql_next_result() functions. These functions are used at the end of a loop that iterates as long as more results are available. Failure to process the result this way may result in a dropped connection to the server.

This leads to the conclusion, that aborting a multiple-statement query is not an intended feature.

Moreover, I didn’t find any resource explaining when subsequent queries are actually executed.
Calling next_result() doesn’t neccessarily mean that the query hasn’t been executed already.

EDIT : TEST CASE

To prove what I previously assumed, I created a test case:

Источник

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

Источник

MySQLi раскладываем все по полочкам

Php mysqli multi query. Смотреть фото Php mysqli multi query. Смотреть картинку Php mysqli multi query. Картинка про Php mysqli multi query. Фото Php mysqli multi query
Для кого это статья? Первоочередной целью написания статьи было именно «разложить все по полочкам» для тех, кто уже работал с mysqli, но не вникал глубоко, а быстренько написал свои обертки и забыл про оригинальный синтаксис. Я постарался разъяснить нюансы, с которым столкнулся сам, при переносе данных из большой и очень старой БД, спроектированной человеком, не знающим про нормализации, в новую, с сильно изменившейся структурой.

Можно ли читать эту статью людям, которые все еще используют старое расширение mysql и только думающие об перехода на PDO или MySqli? Думаю даже нужно.

MySqli или PDO

Последние годы я писал сайты исключительно на фреймворках, что избавляло меня от работы с БД напрямую. Некоторое время назад начал работу над сайтом на чистом php и задался вопросом, что использовать вместо устаревшего и нерекомендованного к использованию старого расширения PHP MySQL.

Выбирать нужно было между MySqli и PDO. После не очень длительного изучения решил остановиться на MySqli, так как, как мне тогда казалось, он полностью идентичен PDO, за исключением того, что нет возможности отказаться от MySQL в пользу чего-то другого. Как я напишу ниже это не совсем так, минимум одно заметное отличие есть.

MySqli рекомендован к использованию самими разработчиками PHP.[1]

ООП и процедурный интерфейс

MySqli позволяет писать код как в ООП стиле так и в процедурном. Мне ближе ООП как и большинству из хабр сообщества, поэтому в этом статье будет использован именно он.

Три основные класса

Соединение с БД

Способ первый. Если вам нужно просто создать соединение.

Способ второй. Если вам нужно использовать опции соединения.

С помощью $mysqli->connect_errno и $mysqli->connect_error мы получаем описание и код ошибки, возникших при соединении. И new mysqli() и $mysqli->real_connect() при ошибках соединений вызывают ошибку PHP Warning. Поэтому вывод ошибок с помощью выше упомянутых функций имеет смысл, если у вас отключено отображение ошибок PHP, например, на рабочем сервере, либо если вам нужно как-то обработать эти данные. Я упомнил здесь об этом, потому что не все функции MySQLi вызывают PHP Warning в случае ошибки, и для того что бы узнать, что произошла ошибка необходимо обязательно обращаться к специальным функциям, об этом ниже.

Полученный при соединении объект мы присвоили переменной $mysqli, для того чтобы использовать его в дальнейшем. Это очевидно для ООП стиля, но и для процедурного стиля этот объект также необходим, в этом отличие от устаревшего расширения MySQL, где ссылку на соединение необязательно было передавать при каждом использовании mysql функций.

Буферизированные и не буферизированные результаты

Прежде чем рассказывать дальше, хотелось бы объяснить разницу между этими двумя типами результатов.

Рассмотрим небуферизированный результат. В этом случае вы можете начинать читать результаты, не дожидаясь пока mysql сервер получит результат полностью.

Буферизированный результат лишен этих недостатков и соответственно лишен перечисленных преимуществ.

«Классические» запросы

В MySqli оставили возможность «классических» запросов: когда пользователю предлагается самостоятельно заниматься безопасностью передаваемых запросов так, как это было в устаревшем расширении MySQL. Для этого предлагается использовать функцию $mysqli->real_escape_string(), с помощью которой необходимо обрабатывать все данные перед помещением их в запрос.

Так же как и с соединением есть два способа сделать такой запрос короткий и длинный.

Возможные константы:
MYSQLI_STORE_RESULT – вернет буферизированный результат, значение по умолчанию
MYSQLI_USE_RESULT – небуферизированный

Функции $mysqli->use_result() или $mysqli->store_result() так же используются при мульти запросах (запросах состоящих из нескольких запросов). Мульти запросы в этой статье рассмотрены не будут.

И тот и другой синтаксисы вернут результат в виде объекта mysqli_result, который представляет собой удобный интерфейс для работы с результатом, как с буферизированным так и не с небуферизированным.

Подготовленные запросы

Два способа создания подготовленного запроса.

Различия в том, для какого объекта вызываются функции получения информации об ошибке. Мне второй способ кажется удобнее, потому что проверки на ошибки можно объединить в один блок if c другими функциями mysqli_stmt. Как это сделать будет видно в примерах ниже.

Класс mysqli_result и работа с результатом с помощью него

Как было показано выше, объект mysqli_result вы могли получить как с помощью «классического» запроса с помощью класса mysqli, тогда он может быть как буферизированный так и небуферизированный, так и с помощью класса mysqli_stmt, тогда он буферизированный. От того какой результат вы получили, зависит работа функций этого класса, поэтому нужно хорошо понимать, что если ваш запрос небуферизированный вы не располагаете всем результатом и соответственно не можете знать сколько строк в результате, и читать его можно только по-порядку строка за строкой.

object ( Book ) [ 4 ]
private ‘some1’ => int 1
public ‘some2’ => int 2
protected ‘id’ => int 382

Источник

mysqli::query

Description

Performs a query against the database.

In the case where you pass a statement to mysqli_query() that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver ( mysqlnd ) or MySQL Client Library ( libmysqlclient ). The behavior is as follows:

Parameters

Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

Security warning: SQL injection

If the query contains any variable input then parameterized prepared statements should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the mysqli_real_escape_string() function.

The result mode can be one of 3 constants indicating how the result will be returned from the MySQL server.

Return Values

Examples

Example #1 mysqli::query() example

The above examples will output something similar to:

See Also

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

Источник

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

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