Execute query with php

PDOStatement::execute

Массив значений, содержащий столько элементов, сколько параметров заявлено в SQL-запросе. Все значения будут приняты, как имеющие тип PDO::PARAM_STR .

Нельзя привязать несколько значений к одному параметру; например, нельзя привязать два значения к именованному параметру в выражении IN().

Нельзя привязать больше значений, чем заявлено в запросе; если в массиве params больше элементов, чем заявлено в SQL-запросе методом PDO::prepare() , выполнение запроса завершится неудачей и будет вызвана ошибка.

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

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Ошибки

Выдаёт ошибку уровня E_WARNING , если атрибуту PDO::ATTR_ERRMODE установлено значение PDO::ERRMODE_WARNING .

Выбрасывает исключение PDOException , если атрибуту PDO::ATTR_ERRMODE установлено значение PDO::ERRMODE_EXCEPTION .

Примеры

Пример #1 Выполнение подготовленного запроса с привязкой переменных и значений

/* Выполнение подготовленного запроса с привязкой переменных и значений */
$calories = 150 ;
$colour = ‘gre’ ;
$sth = $dbh -> prepare ( ‘SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour LIKE :colour' );
$sth -> bindParam ( ‘calories’ , $calories , PDO :: PARAM_INT );
/* Имена также могут начинаться с двоеточия «:» (необязательно) */
$sth -> bindValue ( ‘:colour’ , «% $colour %» );
$sth -> execute ();
?>

Пример #2 Выполнение подготовленного запроса с массивом именованных значений

/* Выполнение подготовленного запроса с передачей массива входных значений */
$calories = 150 ;
$colour = ‘red’ ;
$sth = $dbh -> prepare ( ‘SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour' );
$sth -> execute (array( ‘calories’ => $calories , ‘colour’ => $colour ));
/* Ключи массива также могут начинаться с двоеточия «:» (необязательно) */
$sth -> execute (array( ‘:calories’ => $calories , ‘:colour’ => $colour ));
?>

Пример #3 Выполнение подготовленного запроса с массивом позиционных значений

/* Выполнение подготовленного запроса с передачей массива входных значений */
$calories = 150 ;
$colour = ‘red’ ;
$sth = $dbh -> prepare ( ‘SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?' );
$sth -> execute (array( $calories , $colour ));
?>

Пример #4 Выполнение подготовленного запроса с переменными, привязанными к позиционным заполнителям

/* Выполнение подготовленного запроса с привязкой PHP переменных */
$calories = 150 ;
$colour = ‘red’ ;
$sth = $dbh -> prepare ( ‘SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?' );
$sth -> bindParam ( 1 , $calories , PDO :: PARAM_INT );
$sth -> bindParam ( 2 , $colour , PDO :: PARAM_STR , 12 );
$sth -> execute ();
?>

Пример #5 Выполнение подготовленного запроса с использованием массива для выражения IN

/* Выполнение подготовленного запроса с использованием массива для выражения IN */
$params = array( 1 , 21 , 63 , 171 );
/* Создаём строку из знаков вопроса (?) в количестве, равном количеству параметров */
$place_holders = implode ( ‘,’ , array_fill ( 0 , count ( $params ), ‘?’ ));

/*
В этом примере подготавливается запрос с достаточным количеством неименованных
псевдопеременных (?) для каждого значения из массива $params. Когда запрос будет
выполняться, эти знаки вопроса будут заменены на элементы массива. Это не то же
самое, что использовать PDOStatement::bindParam(), где привязка осуществляется по
ссылке на переменную. PDOStatement::execute() связывает параметры по значению.
*/
$sth = $dbh -> prepare ( «SELECT id, name FROM contacts WHERE id IN ( $place_holders )» );
$sth -> execute ( $params );
?>

Примечания

Замечание:

Для некоторых драйверов необходимо закрывать курсор, прежде чем выполнять следующий запрос.

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

  • PDO::prepare() — Подготавливает запрос к выполнению и возвращает связанный с этим запросом объект
  • PDOStatement::bindParam() — Привязывает параметр запроса к переменной
  • PDOStatement::fetch() — Извлечение следующей строки из результирующего набора
  • PDOStatement::fetchAll() — Выбирает оставшиеся строки из набора результатов
  • PDOStatement::fetchColumn() — Возвращает данные одного столбца следующей строки результирующего набора

User Contributed Notes 31 notes

Hopefully this saves time for folks: one should use $count = $stmt->rowCount() after $stmt->execute() in order to really determine if any an operation such as ‘ update ‘ or ‘ replace ‘ did succeed i.e. changed some data.

Note that you must
— EITHER pass all values to bind in an array to PDOStatement::execute()
— OR bind every value before with PDOStatement::bindValue(), then call PDOStatement::execute() with *no* parameter (not even «array()»!).
Passing an array (empty or not) to execute() will «erase» and replace any previous bindings (and can lead to, e.g. with MySQL, «SQLSTATE[HY000]: General error: 2031» (CR_PARAMS_NOT_BOUND) if you passed an empty array).

Thus the following function is incorrect in case the prepared statement has been «bound» before:

function customExecute ( PDOStatement & $sth , $params = NULL ) <
return $sth -> execute ( $params );
>
?>

and should therefore be replaced by something like:

function customExecute ( PDOStatement & $sth , array $params = array()) <
if (empty( $params ))
return $sth -> execute ();
return $sth -> execute ( $params );
>
?>

Also note that PDOStatement::execute() doesn’t require $input_parameters to be an array.

(of course, do not use it as is ^^).

An array of insert values (named parameters) don’t need the prefixed colon als key-value to work.

/* Execute a prepared statement by passing an array of insert values */
$calories = 150 ;
$colour = ‘red’ ;
$sth = $dbh -> prepare ( ‘SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour' );
// instead of:
// $sth->execute(array(‘:calories’ => $calories, ‘:colour’ => $colour));
// this works fine, too:
$sth -> execute (array( ‘calories’ => $calories , ‘colour’ => $colour ));
?>

This allows to use «regular» assembled hash-tables (arrays).
That realy does make sense!

When passing an array of values to execute when your query contains question marks, note that the array must be keyed numerically from zero. If it is not, run array_values() on it to force the array to be re-keyed.

$anarray = array( 42 => «foo» , 101 => «bar» );
$statement = $dbo -> prepare ( «SELECT * FROM table WHERE col1 = ? AND col2 = ?» );

//This will not work
$statement -> execute ( $anarray );

//Do this to make it work
$statement -> execute ( array_values ( $anarray ));
?>

When using a prepared statement to execute multiple inserts (such as in a loop etc), under sqlite the performance is dramatically improved by wrapping the loop in a transaction.

I have an application that routinely inserts 30-50,000 records at a time. Without the transaction it was taking over 150 seconds, and with it only 3.

This may affect other implementations as well, and I am sure it is something that affects all databases to some extent, but I can only test with PDO sqlite.

$data = array(
array( ‘name’ => ‘John’ , ‘age’ => ’25’ ),
array( ‘name’ => ‘Wendy’ , ‘age’ => ’32’ )
);

try <
$pdo = new PDO ( ‘sqlite:myfile.sqlite’ );
>

catch( PDOException $e ) <
die( ‘Unable to open database connection’ );
>

$insertStatement = $pdo -> prepare ( ‘insert into mytable (name, age) values (:name, :age)’ );

// start transaction
$pdo -> beginTransaction ();

// end transaction
$pdo -> commit ();

?>

[EDITED BY sobak: typofixes by Pere submitted on 12-Sep-2014 01:07]

«You cannot bind more values than specified; if more keys exist in input_parameters than in the SQL specified in the PDO::prepare(), then the statement will fail and an error is emitted.» However fewer keys may not cause an error.

As long as the number of question marks in the query string variable matches the number of elements in the input_parameters, the query will be attempted.

This happens even if there is extraneous information after the end of the query string. The semicolon indicates the end of the query string; the rest of the variable is treated as a comment by the SQL engine, but counted as part of the input_parameters by PHP.

Have a look at these two query strings. The only difference is a typo in the second string, where a semicolon accidentally replaces a comma. This UPDATE query will run, will be applied to all rows, and will silently damage the table.

/**
* Query is intended to UPDATE a subset of the rows based on the WHERE clause
*/
$sql = «UPDATE my_table SET fname = ?, lname = ? WHERE > ;

/**
* Query UPDATEs all rows, ignoring everything after the semi-colon, including the WHERE clause!
*
* Expected (but not received):
*
*** Warning:
*** PDOStatement::execute():
*** SQLSTATE[HY093]:
*** Invalid parameter number: number of bound variables does not match number of tokens.
*
*/
// Typo here ———————— |
// V
$sql = «UPDATE my_table SET fname = ?; lname = ? WHERE > ; // One token in effect
$pdos = $pdo -> prepare ( $sql );
$pdos -> execute ( [ ‘foo’ , ‘bar’ , 3 ] ); // Three input_parameters
?>

PHP 5.4.45, mysqlnd 5.0.10

Источник

mysqli_execute_query

Prepares the SQL query, binds parameters, and executes it. The mysqli::execute_query() method is a shortcut for mysqli::prepare() , mysqli_stmt::bind_param() , mysqli_stmt::execute() , and mysqli_stmt::get_result() .

The statement template can contain zero or more question mark ( ? ) parameter markers⁠—also called placeholders. The parameter values must be provided as an array using params parameter.

A prepared statement is created under the hood but it’s never exposed outside of the function. It’s impossible to access properties of the statement as one would do with the mysqli_stmt object. Due to this limitation, the status information is copied to the mysqli object and is available using its methods, e.g. mysqli_affected_rows() or mysqli_error() .

  • On Linux returns an error code of 1153. The error message means got a packet bigger than max_allowed_packet bytes .
  • On Windows returns an error code 2006. This error message means server has gone away .

Parameters

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

The query, as a string. It must consist of a single SQL statement.

The SQL statement may contain zero or more parameter markers represented by question mark ( ? ) characters at the appropriate positions.

Note:

The markers are legal only in certain places in SQL statements. For example, they are permitted in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value. However, they are not permitted for identifiers (such as table or column names).

An optional list array with as many elements as there are bound parameters in the SQL statement being executed. Each value is treated as a string .

Return Values

Returns false on failure. For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN , returns a mysqli_result object. For other successful queries, returns true .

Examples

Example #1 mysqli::execute_query() example

mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = new mysqli ( ‘localhost’ , ‘my_user’ , ‘my_password’ , ‘world’ );

$query = ‘SELECT Name, District FROM City WHERE CountryCode=? ORDER BY Name LIMIT 5’ ;
$result = $mysqli -> execute_query ( $query , [ ‘DEU’ ]);
foreach ( $result as $row ) printf ( «%s (%s)\n» , $row [ «Name» ], $row [ «District» ]);
>

mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$link = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );

$query = ‘SELECT Name, District FROM City WHERE CountryCode=? ORDER BY Name LIMIT 5’ ;
$result = mysqli_execute_query ( $link , $query , [ ‘DEU’ ]);
foreach ( $result as $row ) printf ( «%s (%s)\n» , $row [ «Name» ], $row [ «District» ]);
>

The above examples will output something similar to:

Aachen (Nordrhein-Westfalen) Augsburg (Baijeri) Bergisch Gladbach (Nordrhein-Westfalen) Berlin (Berliini) Bielefeld (Nordrhein-Westfalen)

See Also

  • mysqli_prepare() — Prepares an SQL statement for execution
  • mysqli_stmt_execute() — Executes a prepared statement
  • mysqli_stmt_bind_param() — Binds variables to a prepared statement as parameters
  • mysqli_stmt_get_result() — Gets a result set from a prepared statement as a mysqli_result object

User Contributed Notes

Источник

Читайте также:  Перемешать строки датафрейма питон
Оцените статью