mysqli query что возвращает
Функция Mysqli_query
Функция Mysqli_query выполняет запрос к базе данных MySQL.
Параметр Link являет собой идентификатор соединения, полученный с помощью Mysqli_connect.
Параметр Query должен содержать текст запроса.
Параметр Resultmode может содержать константу MYSQLI_USE_RESULT, либо MYSQLI_STORE_RESULT, которая установлена по умолчанию. При использовании MYSQLI_USE_RESULT все последующие вызовы этой функции будут возвращать ошибку Commands out of sync до тех пор, пока не будет вызвана функция Mysqli_free_result.
Функция возвращает FALSE в случае неудачи. В случае успешного выполнения запросов SELECT, SHOW, DESCRIBE или EXPLAIN вернет объект Mysqli_result. Для остальных успешных запросов Mysqli_query вернет TRUE.
Пример использования функции Mysqli_query:
Результат успешного выполнения:
Кроме данной функции за выполнение запросов также отвечают функции Mysqli_real_query и Mysqli_multi_query. Чаще всего применяется функция Mysqli_query, так как она выполняет сразу две задачи: выполняет запрос и буферизует на клиенте результат этого запроса. Вызов Mysqli_query идентичен последовательному вызову функций Mysqli_real_query и Mysqli_store_result.
Буферизация на клиенте позволяет серверу очень быстро освобождать занятые запросом ресурсы. Построчное же чтение и дальнейшая обработка результатов клиентом довольно медленный процесс. Поэтому рекомендуется использовать буферизацию результирующих наборов именно функцией Mysqli_query.
Обработка результатов на клиенте проще, нежели средствами сервера. PHP приложения могут свободно оперировать данными внутри буферизованных результирующих наборов. Быстрая навигация по строкам наборов обусловлена тем, что наборы полностью располагаются в памяти клиента.
mysql_query
mysql_query — Посылает запрос MySQL
Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:
Описание
Список параметров
Запрос не должен заканчиваться точкой с запятой. Данные в запросе должны быть корректно проэкранированы.
Возвращаемые значения
Для запросов SELECT, SHOW, DESCRIBE, EXPLAIN и других запросов, возвращающих результат из нескольких рядов, mysql_query() возвращает дескриптор результата запроса ( resource ), или false в случае возникновения ошибки.
Для других типов SQL-запросов, INSERT, UPDATE, DELETE, DROP и других, mysql_query() возвращает true в случае успешного выполнения и false в случае возникновения ошибки.
Полученный дескриптор результата нужно передать в функцию mysql_fetch_assoc() или любую другую функцию, работающую с результатами запросов.
Используйте mysql_num_rows() для выяснения количества рядов в результате SELECT-запроса или mysql_affected_rows() для выяснения количества обработанных рядов запросами DELETE, INSERT, REPLACE и UPDATE.
Примеры
Пример #1 Неверный запрос
Пример #2 Верный запрос
// Эти данные, к примеру, могли быть получены от пользователя
$firstname = ‘fred’ ;
$lastname = ‘fox’ ;
Смотрите также
User Contributed Notes 26 notes
Simulating an atomic operation for application locks using mysql.
$q = «update `table` set `LOCK`=’F’ where `ID`=’1′»;
$lock = mysql_affected_rows();
If we assume
NOT LOCKED = «» (empty string)
LOCKED = ‘F’
then if the column LOCK had a value other than F (normally should be an empty string) the update statement sets it to F and set the affected rows to 1. Which mean than we got the lock.
If affected rows return 0 then the value of that column was already F and somebody else has the lock.
The secret lies in the following statement taken from the mysql manual:
«If you set a column to the value it currently has, MySQL notices this and does not update it.»
Of course all this is possible if the all application processes agree on the locking algorithm.
mysql_query doesnt support multiple queries, a way round this is to use innodb and transactions
this db class/function will accept an array of arrays of querys, it will auto check every line for affected rows in db, if one is 0 it will rollback and return false, else it will commit and return true, the call to the function is simple and is easy to read etc
———-
function transaction($q_array) <
$retval = 1;
if($retval == 0) <
$this->rollback();
return false;
>else <
$this->commit();
return true;
>
>
/* Create database connection object */
$database = new MySQLDB;
// then from anywhere else simply put the transaction queries in an array or arrays like this:
$q = array (
array(«query» => «UPDATE table WHERE something = ‘something'»),
array(«query» => «UPDATE table WHERE something_else = ‘something_else'»),
array(«query» => «DELETE FROM table WHERE something_else2 = ‘something_else2′»),
);
Regarding the idea for returning all possible values of an enum field, the mySQL manual says that «SHOW COLUMNS FROM table LIKE column» should be used to do this.
The function below (presumes db connection) will return an array of the possible values of an enum.
function GetEnumValues($Table,$Column)
<
$dbSQL = «SHOW COLUMNS FROM «.$Table.» LIKE ‘».$Column.»‘»;
$dbQuery = mysql_query($dbSQL);
$EnumValues = substr($EnumValues, 6, strlen($EnumValues)-8);
$EnumValues = str_replace(«‘,'»,»,»,$EnumValues);
This is just a quick example to show how to do it, some tidying up needs to be done (ie checking if the field is actually an enum) before it is perfect.
This project implements a wrapper to mysql functions in PHP7.0+
tested and working fine =)
When trying to INSERT or UPDATE and trying to put a large amount of text or data (blob) into a mysql table you might run into problems.
In mysql.err you might see:
Packet too large (73904)
You would just replace maxsize with the max size you want to insert, the default is 65536
It should be noted that mysql_query can generate an E_WARNING (not documented). The warning that I hit was when the db user did not have permission to execute a UDF.
Expected behavior would be like an Invalid SQL statement, where there is no E_WARNING generated by mysql_query.
Warning: mysql_query() [function.mysql-query]: Unable to save result set in filename.php
The mysql_errno is 1370 and the mysql_error is:
execute command denied to user ‘username’@’%’ for routine ‘database_name.MyUDF’
If, like me, you come from perl, you may not like having to use sprintf to ‘simulate’ placeholders that the DBI package from perl provides. I have created the following wrapper function for mysql_query() that allows you to use ‘?’ characters to substitute values in your DB queries. Note that this is not how DBI in perl handles placeholders, but it’s pretty similar.
// oops, wrong userid or passwd
else <
echo «Invalid username and password combination.\n» ;
>
?>
When you run a select statement and receive a response, the data types of your response will be a string regardless of the data type of the column.
Use this to neatly insert data into a mysql table:
I believe there is a typo in celtic at raven-blue dot com version with:
I think you really ment:
Keep in mind when dealing with PHP & MySQL that sending a null-terminated string to a MySQL query can be misleading if you use echo($sql) in PHP because the null terminator may not be visible.
For example (this assumes connection is already made),
$string1 = «mystring\0»;
$string2 = «mystring»;
$query1 = «SELECT * FROM table WHERE mystring='».$string1.»‘»
$query2 = «SELECT * FROM table WHERE mystring='».$string2.»‘»
//but printing these queries to the screen will provide the same result
echo($result1);
echo($result2);
Not knowing this could lead to some mind-numbing troubleshooting when dealing with any strings with a null terminator. So now you know! 🙂
this could be a nice way to print values from 2 tables with a foreign key. i have not yet tested correctly but it should work fine.
Here’s a parameterised query function for MySQL similar to pg_query_params, I’ve been using something similar for a while now and while there is a slight drop in speed, it’s far better than making a mistake escaping the parameters of your query and allowing an SQL injection attack on your server.
# Parameterised query implementation for MySQL (similar PostgreSQL’s PHP function pg_query_params)
# Example: mysql_query_params( «SELECT * FROM my_table WHERE col1=$1 AND col2=$2», array( 42, «It’s ok» ) );
For all you programmers out there getting the ‘Command out of synch’ errors when executing a stored procedure call:
There are known bugs related to this issue, and the best workaround for avoiding this error seems to be switching to mysqli.
Still, I needed mysql to also handle these calls correctly.
The error is normally related to wrong function call sequences, though the bug report at http://bugs.php.net/bug.php?id=39727 shows otherwise.
For me, after commenting out hundreds of lines and several introspection calls to parse the procedure information (using information_schema and ‘SHOW’ extensions), I still got the same error.
The first result is returned, because I initiated my connection using the MYSQL_MULTI_RESULTS value of 131072 (forget this and you will never get any output, but an error message stating mysql cannot return results in this context)
After testing with this code (sproc2 simply calls ‘SELECT * FROM sometable’), I found the error must be in the mysql library/extension. Somehow, mysql does not handle multiple resultsets correctly, or is at least missing some functionality related to handling multiple results.
So if you ever make a uniform database accessing interface and implement stored procedures/prepared statements (or classes for it), this could be a solution if you really wish to enable stored procedures.
Still, be aware that this is really a serious flaw in your design (and IMHO, the mysql extension)
Also see the documentation for mysqli on mysqli_query, which seems to be working fine.
here’s a script for parsing a *.sql file (tested only on dumps created with phpMyAdmin) which is short and simple (why do people say «here’s a short and simple script» and it has a 100 lines?). the script skips comments and allows ; to be present within the querys
I much prefer to use the same syntax for single INSERT, REPLACE and UPDATE queries as it is easier to read and keeps my code shorter (no seperate building of insert and update values)
INSERT INTO table SET x=’1′, y=3
UPDATE table SET x=’2′ WHERE y=3
So if your using a function to build your query, you will only ever need to code the «field=value, field2=value2» part for any query.
/* malformed query /*
$rs = mysql_query(«SELECT `foo` FRO `bar`»);
if($rs) <
echo «This will never be echoed»;
>
?>
One way to reduce the dangers of queries like the dlete command above that dletes the whole DB is to use limits wherever possible.
EG. If you have a routine that is only deisnged to delete 1 record, add ‘LIMIT 1’ to the end of the command. This way you’ll only lose one record if someone does something stupid.
Just don’t trust ANY data that is sent to your script.
If you need to execute sevaral SQL commands in a row (usually called batcg SQL) using PHP you canot use mysql_query() since it can execute single command only.
Here is simple but effective function that can run batch SQL commands. Take cere, if string contains semicolon (;) anywhere except as command delimiter (within string expression for example) function will not work.
For those of you whom spent hours bashing your brains against the keyboard wondering why your non-English characters are output as question marks. Try the following:
?>
Simply run the query «set names ‘utf8’ » against the MySQL DB and your output should appear correct.
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
Работа с MySQL в PHP
PHP поддерживает работу с базой данных MySQL.
Специальные встроенные функции для работы с MySQL позволяют просто и эффективно работать с этой СУБД: выполнять любые запросы, читать и записывать данные, обрабатывать ошибки.
Сценарий, который подключается к БД, выполняет запрос и показывает результат, будет состоять всего из нескольких строк. Для работы с MySQL не надо ничего дополнительно устанавливать и настраивать; всё необходимое уже доступно вместе со стандартной поставкой PHP.
Что такое mysqli?
mysqli (MySQL Improved) — это расширение PHP, которое добавляет в язык полную поддержку баз данных MySQL. Это расширение поддерживает множество возможностей современных версий MySQL.
Как выглядит работа с базой данных
Типичный процесс работы с СУБД в PHP-сценарии состоит из нескольких шагов:
Функция mysqli connect: соединение с MySQL
Но чтобы выполнить соединение с сервером, необходимо знать как минимум три параметра:
Базовый синтаксис функции mysqli_connect() :
Проверка соединения
Первое, что нужно сделать после соединения с СУБД — это выполнить проверку, что оно было успешным.
Эта проверка нужна, чтобы исключить ошибку при подключении к БД. Неверные параметры подключения, неправильная настройка или высокая нагрузка заставит MySQL отвеграть новые подключения. Все эти ситуации приведут к невозможности соединения, поэтому программист должен проверить успешность подключения к серверу, прежде чем выполнять следующие действия.
Соединение с MySQL и проверка на ошибки:
Функция mysqli_connect_error() просто возвращает текстовое описание последней ошибки MySQL.
Установка кодировки
Первым делом после установки соединения крайне желательно явно задать кодировку, которая будет использоваться при обмене данными с MySQL. Если этого не сделать, то вместо записей со значениями, написанными кириллицей, можно получить последовательность из знаков вопроса: ‘. ’.
Вызови эту функцию сразу после успешной установки соединения: mysqli_set_charset($con, «utf8»);
Выполнение запросов
Установив соединение и определив кодировку мы готовы выполнить свои первые SQL-запросы. Вы уже умеете составлять корректные SQL команды и выполнять их через консольный или визуальный интерфейс MySQL-клиента.
Те же самые запросы можно отправлять без изменений и из PHP-сценария. Помогут в этом несколько встроенных функций языка.
Два вида запросов
Следует разделять все SQL-запросы на две группы:
При выполнении запросов из среды PHP, запросы из второй группы возвращают только результат их исполнения: успех или ошибку.
Запросы первой группы при успешном выполнении возвращают специальный ресурс результата. Его, в свою очередь, можно преобразовать в ассоциативный массив (если нужна одна запись) или в двумерный массив (если требуется список записей).
Добавление записи
Вернёмся к нашему проекту — дневнику наблюдений за погодой. Начнём практическую работу с заполнения таблиц данными. Для начала добавим хотя бы один город в таблицу cities.
Выражение INSERT INTO используется для добавления новых записей в таблицу базы данных.
Функция insert id: как получить идентификатор добавленной записи
Теперь у нас есть всё необходимое, чтобы добавить погодную запись.
Вот как будет выглядеть комплексный пример с подключением к MySQL и добавлением двух новых записей:
Чтение записей
В этом примере показано, как вывести все существующие города из таблицы cities:
Чтобы получить действительные данные, то есть записи из таблицы, следует использовать другую функцию — mysqli_fetch_array() — и передать ей единственным параметром эту самую ссылку.
Теперь каждый вызов функции mysqli_fetch_array() будет возвращать следующую запись из всего результирующего набора записей в виде ассоциативного массива.
Цикл while здесь используется для «прохода» по всем записям из полученного набора записей.
Значение поля каждой записи можно узнать просто обратившись по ключу этого ассоциативного массива.
Как получить сразу все записи в виде двумерного массива
Иногда бывает удобно после запроса на чтение не вызывать в цикле mysqli_fetch_array для извлечения очередной записи по порядку, а получить их сразу все одним вызовом. PHP так тоже умеет. Функция mysqli_fetch_all($res, MYSQLI_ASSOC) вернёт двумерный массив со всеми записями из результата последнего запроса.
Перепишем пример с показом существующих городов с её использованием: