Php mysqli query syntax

PHP mysqli_query() Function

The mysqli_query() function accepts a string value representing a query as one of the parameters and, executes/performs the given query on the database.

Syntax

Parameters

This is an object representing a connection to MySQL Server.

This is a string value representing the query to be executed.

This is a integer value representing the result mode. You can pass MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT as values to this parameter.

Return Values

For SELECT, SHOW, DESCRIBE and EXPLAIN queries this function returns a mysqli_result object holding the result of the query in case of success and, false if failed.

For other queries this function returns an boolean value which is, true if the operation/query is successful and, false if not.

PHP Version

This function was first introduced in PHP Version 5 and works works in all the later versions.

Example

Following example demonstrates the usage of the mysqli_query() function (in procedural style) −

This will produce following result −

Table Created . Records Inserted .

If you observe the contents of the table in the database you can see the inserted records as shown below −

mysql> select * from my_team; +------+------------+------------+----------------+-------------+ | ID | First_Name | Last_Name | Place_Of_Birth | Country | +------+------------+------------+----------------+-------------+ | 1 | Shikhar | Dhawan | Delhi | India | | 2 | Jonathan | Trott | CapeTown | SouthAfrica | | 3 | Kumara | Sangakkara | Matale | Srilanka | | 4 | Virat | Kohli | Delhi | India | +------+------------+------------+----------------+-------------+ 4 rows in set (0.00 sec)

Example

In object oriented style the syntax of this function is $con->query(); Following is the example of this function in object oriented style $minus;

query("CREATE TABLE IF NOT EXISTS players(First_Name VARCHAR(255), Last_Name VARCHAR(255), Country VARCHAR(255))"); $con->query("insert into players values('Shikhar', 'Dhawan', 'India')"); $con->query("insert into players values('Jonathan', 'Trott', 'SouthAfrica')"); print("Data Created. "); //Closing the connection $res = $con -> close(); ?>

This will produce following result −

If you observe the contents of the table in the database you can see the inserted records as shown below −

mysql> select * from players; +------------+-----------+-------------+ | First_Name | Last_Name | Country | +------------+-----------+-------------+ | Shikhar | Dhawan | India | | Jonathan | Trott | SouthAfrica | +------------+-----------+-------------+ 2 rows in set (0.00 sec)

Example

Following example prints the results of INSERT and SELECT queries −

This will produce following result −

Table Created . Result of Insert Query: 1 Result of Insert Query: 1Result of the SELECT query: mysqli_result Object ( [current_field] => 0 [field_count] => 5 [lengths] => [num_rows] => 2 [type] => 0 )

Example

Assume we have created a table players in the database and populated it, as shown below −

CREATE TABLE Players (Name VARCHAR(255), Age INT, Score INT); insert into Players values('Dhavan', 33, 90),('Rohit', 28, 26),('Kohli', 25, 50);

Following example retrieves the resultset from a

 > //Closing the connection mysqli_close($con); ?>

This will produce following result −

Name: Dhavan Age: 33 Name: Rohit Age: 28 Name: Kohli Age: 25

Источник

mysqli_query

Для не-DML запросов (не INSERT, UPDATE или DELETE), эта функция равносильна вызову функции mysqli_real_query() , а затем mysqli_use_result() или mysqli_store_result() .

  • mysqlnd на платформе Linux возвращает код ошибки 1153. Сообщение об ошибке означает » размер пакета превышает max_allowed_packet байт «.
  • mysqlnd на платформе Windows возвращает код ошибки 2006. Это сообщение об ошибке означает » отказ сервера «.
  • libmysqlclient на всех платформах возвращает код ошибки 2006. Это сообщение об ошибке означает » отказ сервера «.

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

Только для процедурного стиля: Идентификатор соединения, полученный с помощью mysqli_connect() или mysqli_init()

Данные в тексте запроса должны быть правильно экранированы.

Либо константа MYSQLI_USE_RESULT , либо MYSQLI_STORE_RESULT в зависимости от требуемого поведения функции. По умолчанию используется MYSQLI_STORE_RESULT .

При использовании MYSQLI_USE_RESULT все последующие вызовы этой функции будут возвращать ошибку Commands out of sync до тех пор, пока не будет вызвана функция mysqli_free_result()

С константой MYSQLI_ASYNC (доступна при использовании mysqlnd) возможно выполнять запросы асинхронно. В этом случае для получения результатов каждого запроса необходимо использовать функцию mysqli_poll() .

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

Возвращает FALSE в случае неудачи. В случае успешного выполнения запросов SELECT, SHOW, DESCRIBE или EXPLAIN mysqli_query() вернет объект mysqli_result. Для остальных успешных запросов mysqli_query() вернет TRUE .

Список изменений

Версия Описание
5.3.0 Добавлена возможность выполнять асинхронные запросы.

Примеры

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

$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );

/* проверка соединения */
if ( $mysqli -> connect_errno ) printf ( «Не удалось подключиться: %s\n» , $mysqli -> connect_error );
exit();
>

/* Создание таблицы не возвращает результирующего набора */
if ( $mysqli -> query ( «CREATE TEMPORARY TABLE myCity LIKE City» ) === TRUE ) printf ( «Таблица myCity успешно создана.\n» );
>

/* Select запросы возвращают результирующий набор */
if ( $result = $mysqli -> query ( «SELECT Name FROM City LIMIT 10» )) printf ( «Select вернул %d строк.\n» , $result -> num_rows );

/* очищаем результирующий набор */
$result -> close ();
>

/* Если нужно извлечь большой объем данных, используем MYSQLI_USE_RESULT */
if ( $result = $mysqli -> query ( «SELECT * FROM City» , MYSQLI_USE_RESULT ))

/* Важно заметить, что мы не можем вызывать функции, которые взаимодействуют
с сервером, пока не закроем результирующий набор. Все подобные вызовы
будут вызывать ошибку ‘out of sync’ */
if (! $mysqli -> query ( «SET @a:=’this will not work'» )) printf ( «Ошибка: %s\n» , $mysqli -> error );
>
$result -> close ();
>

$link = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );

/* проверка соединения */
if ( mysqli_connect_errno ()) printf ( «Не удалось подключиться: %s\n» , mysqli_connect_error ());
exit();
>

/* Создание таблицы не возвращает результирующего набора */
if ( mysqli_query ( $link , «CREATE TEMPORARY TABLE myCity LIKE City» ) === TRUE ) printf ( «Таблица myCity успешно создана.\n» );
>

/* Select запросы возвращают результирующий набор */
if ( $result = mysqli_query ( $link , «SELECT Name FROM City LIMIT 10» )) printf ( «Select вернул %d строк.\n» , mysqli_num_rows ( $result ));

/* очищаем результирующий набор */
mysqli_free_result ( $result );
>

/* Если нужно извлечь большой объем данных, используем MYSQLI_USE_RESULT */
if ( $result = mysqli_query ( $link , «SELECT * FROM City» , MYSQLI_USE_RESULT ))

/* Важно заметить, что мы не можем вызывать функции, которые взаимодействуют
с сервером, пока не закроем результирующий набор. Все подобные вызовы
будут вызывать ошибку ‘out of sync’ */
if (! mysqli_query ( $link , «SET @a:=’this will not work'» )) printf ( «Ошибка: %s\n» , mysqli_error ( $link ));
>
mysqli_free_result ( $result );
>

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

Таблица myCity успешно создана. Select вернул 10 строк. Ошибка: Commands out of sync; You can't run this command now

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

  • mysqli_real_query() — Выполнение SQL запроса
  • mysqli_multi_query() — Выполняет запрос к базе данных
  • mysqli_free_result() — Освобождает память занятую результатами запроса

Источник

Читайте также:  Селекторы в CSS3
Оцените статью