Show message when the database was not updated

1

I have a form that updates a record in a database. (Works correctly). The problem is that when the condition where is not met, it shows correct update, although it is not updated.

How do I do it so that when it does not update, it tells me it is not updated

<form method="POST" action="update.php">
  <label for="pedido"># Pedido</label>
  <input type="text" name="pedido" id="doc">
  <label for="texto">Valor abono</label>
  <input type="text" name="pagoabono"  id="texto">
  <input type="submit" value="Enviar abono" name="btn_abono">
</form>

<?php
 if(isset($_POST['btn_abono'])) {
   include("abrir_conexion.php");
   $pedido    = $_POST[ 'pedido' ];
   $pagoabono = $_POST[ 'pagoabono' ];
   $conex = mysqli_connect($host,$usuariodb,$clavedb,$basededatos);
  // Check connection
  if (mysqli_connect_errno()) {
  echo "Fallo la conexion: " . mysqli_connect_error();
  }
  mysqli_query ($conex, "UPDATE $tabla_db1 SET pagoabono ='$pagoabono' where pedido= '$pedido'")
  or die("No se actualizo");
  include("cerrar_conexion.php");
  echo("Actualizacion correcta");
  }
?>
    
asked by Daniel 21.06.2017 в 22:58
source

2 answers

2

You need to get the affected rows, you can do it with:

mysqli_affected_rows($conex);

only verifies that the affected rows are greater than 0, the number of rows affected is the number of records that were updated, if the affected rows are 0, it means that no rows fulfilled the where , so they were not updated .

mysqli_query ($conex, "UPDATE $tabla_db1 SET pagoabono ='$pagoabono' where pedido= '$pedido'")
  or die("No se actualizo");
  if (mysqli_affected_rows($conex)>0){
     echo("Actualizacion correcta");
  } else {
     echo("Pedido no encontrado");
  }
  include("cerrar_conexion.php");

You should also keep in mind that your query is susceptible to SQL injection attacks, try to take a look around:

How to avoid injection SQL in PHP?

    
answered by 21.06.2017 в 23:06
1

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).
    
        
    answered by 22.06.2017 в 00:44