I show you an example of MySQLi used update.
The code is explained in the comments.
Basically the steps would be, once the connection is obtained.
Write the query, applying the query criteria prepared for prevent SQL Injection .
Assign in variables the values that will be used in the query
Prepare the query using prepare
Evaluate if the preparation was successful. You may not succeed if for example you write a table name that does not exist or you make syntax errors in the query
If the preparation is correct, you make bind
of the values you want to update. In this way the values travel separated from the SQL statement itself, so that SQL injection is difficult, almost is avoided. I say this because nothing is 100% safe.
You execute the query and evaluate the result of the execution at the same time. execute
will return true
if the execution was successful, then you can show a message with the number of rows affected by the update, using for it affected_rows
You close the resources of place.
Note: The data of tables and columns were put for test in the demo, you must replace them with yours.
I hope it serves you.
code
VIEW DEMO
<?php
require "util/public_db_info.php";
$mysqli = new mysqli($host_name, $user_name, $pass_word, $database_name, $port);
/*
* Las consultas preparadas sustituyen los valores reales
* por signos de interrogación en MySQLi
*/
$sql = "UPDATE books SET title=? WHERE id=?";
/*
* Almacenar en variables los datos a usar
* Cambia las variables puestas a mano
* por las variables tuyas
*/
$titulo= "Gracias a la vida";
$id= 2;
//Preparar la consulta
$stmt=$mysqli->prepare($sql);
//Evaluar si la preparación tuvo éxito
if ($stmt){
/*
* Pasar parámetros separados de la instrucción SQL
* la letras "si" indican el tipo de cada dato que se va a insertar
* s: String, si es una cadena , i: Integer, si fuera un entero, etc
* Ejecutar
*/
$stmt->bind_param("si", $titulo,$id);
/*
* Verificar el resultado de la ejecución
* sabiendo que, en el caso de UPDATE, como en el caso
* de INSERT, $stmt devuelve TRUE si fue exitosos
*/
if ($stmt->execute()) {
/*
* Imprimir la cantidad de filas actualizadas usando affected_rows
*/
printf("%d Fila(s) actualizada(s).\n", $stmt->affected_rows);
}
else
{
echo "No se pudo actualizar";
}
/*
* Cerrar $stmt para liberar recursos
*/
$stmt->close();
}
else
{
echo "Hubo un error preparando la consulta";
}
/*
* Cerrar conexión a la bd para liberar recursos
*/
$mysqli->close();
?>
result
1 Fila(s) actualizada(s).