mysqli_stmt::execute

mysqli_stmt_execute

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::execute -- mysqli_stmt_executeEjecuta una consulta preparada

Descripción

Estilo orientado a objetos

public mysqli_stmt::execute(?array $params = null): bool

Estilo por procedimientos

mysqli_stmt_execute(mysqli_stmt $statement, ?array $params = null): bool

Ejecuta una consulta que ha sido previamente preparada utilizando la función mysqli_prepare(), gracias al recurso stmt. Durante la ejecución, todas las variables de la consulta serán reemplazadas por los datos apropiados.

Si la consulta es UPDATE, DELETE, o INSERT, el número total de filas afectadas está disponible a través de la función mysqli_stmt_affected_rows(). Si la consulta produce un conjunto de resultados, puede ser recuperado utilizando la función mysqli_stmt_get_result() o recuperándolo línea por línea directamente desde la instrucción utilizando la función mysqli_stmt_fetch().

Parámetros

stmt

Sólo estilo por procediminetos: Un identificador de declaraciones devuelto por mysqli_stmt_init().

params

Una lista opcional, como array, con tantos elementos como parámetros enlazados haya en la instrucción SQL en curso de ejecución. Cada valor es tratado como una string.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

Historial de cambios

Versión Descripción
8.1.0 El parámetro opcional params ha sido añadido.

Ejemplos

Ejemplo #1 Ejecutar una instrucción preparada con variables enlazadas

Estilo orientado a objetos

<?php

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

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

/* Preparación de la consulta */
$stmt = $mysqli->prepare("INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)");

/* Enlazar las variables a los parámetros */
$stmt->bind_param("sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Ejecutar la instrucción */
$stmt->execute();
$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Ejecutar la instrucción */
$stmt->execute();

/* Recuperación de todas las líneas de myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
$result = $mysqli->query($query);
while (
$row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}

Estilo por procedimientos

<?php

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

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

/* Preparación de la consulta */
$stmt = mysqli_prepare($link, "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)");

/* Enlazar las variables a los parámetros */
mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Ejecutar la instrucción */
mysqli_stmt_execute($stmt);
$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Ejecutar la instrucción */
mysqli_stmt_execute($stmt);

/* Recuperación de todas las líneas de myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
$result = mysqli_query($link, $query);
while (
$row = mysqli_fetch_row($result)) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}

El resultado de los ejemplos sería:

Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)

Ejemplo #2 Ejecutar una instrucción preparada con un array de valores

Estilo orientado a objetos

<?php

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

$mysqli->query('CREATE TEMPORARY TABLE myCity LIKE City');

/* Preparación de la consulta */
$stmt = $mysqli->prepare('INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)');

/* Ejecutar la instrucción */
$stmt->execute(['Stuttgart', 'DEU', 'Baden-Wuerttemberg']);

/* Recuperación de todas las líneas de myCity */
$query = 'SELECT Name, CountryCode, District FROM myCity';
$result = $mysqli->query($query);
while (
$row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}

Estilo por procedimientos

<?php

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

mysqli_query($link, 'CREATE TEMPORARY TABLE myCity LIKE City');

/* Preparación de la consulta */
$stmt = mysqli_prepare($link, 'INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)');

/* Ejecutar la instrucción */
mysqli_stmt_execute($stmt, ['Stuttgart', 'DEU', 'Baden-Wuerttemberg']);

/* Recuperación de todas las líneas de myCity */
$query = 'SELECT Name, CountryCode, District FROM myCity';
$result = mysqli_query($link, $query);
while (
$row = mysqli_fetch_row($result)) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}

El resultado de los ejemplos sería:

Stuttgart (DEU,Baden-Wuerttemberg)

Ver también

add a note

User Contributed Notes 1 note

up
13
Typer85 at gmail dot com
18 years ago
Just to clarify this note in the Manual regarding this function:

"Note: When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries."

This is because this function DOES NOT store the result set on the client side so you have to fetch everything in the result set or else you risk major errors.

If you however use the function mysqli_stmt_store_result immediately after you use this function, you are forcing the result set to be stored on the client side and thus it is safe to issue extra queries before fetching all the data.

This is where you really have to make a choice regarding on your application's priorities. If you know your result set is memory hefty, then its a good idea not to store it on the client side so you don't run in any errors regarding unavailable memory on the server. But this also means your not going to do a lot of calculations on the result set or else you will prevent any other usage of the table to which the result set came from until you fetched it all.

If your going to do a lot of calculations or your result set is not memory hefty, its probably a good idea to store it on the client side.

Most of these problems can easily be solved if you have a lot of memory available on your server but thats usually not the case for those on shared hosting.

An intelligent way to counter this problem if your on a shared host is to be smart in the way you design your queries. Try to limit the result set if you know you will be fetching memory hefty result sets.

Test different alternatives for your application and see what works best for you under different conditions.

Good Luck,
To Top