How do I create an IF condition in case my insertion of data in the database is incorrect?

0

I am working on an insertion of data from a formative php to a database (mysql), I want the code to warn me or show an error message in 'echo' in case the query variable $ Result throw an error

PHP-HTML CODE

    <?php
        $con=mysqli_connect ('127.0.0.1','root','','freatico') or die ('ERROR EN LA CONEXION A LA BASE DE DATOS');
        $sql="INSERT INTO puntos VALUES ('".$_POST['idp']."','".$_POST['locali']."','".$_POST['ultmed']."','".$_POST['vref']."','".$_POST['altubo']."','".$_POST['sms']."')";
        $resultado=mysqli_query($con,$sql) or die ('ERROR EN EL QUERY DATABASE');
        if($resultado){
            if( mysqli_num_rows( $resultado )<=0){

                echo 'EL PUNTO QUE ACABA DE REGISTRAR YA EXISTE';
        }
    }
        mysqli_close ($con);
    ?>

I thank you if you help me to reconstruct my code so that I can do what I need.

    
asked by Ângel Dâvíd Bermëo 22.05.2018 в 17:14
source

2 answers

0

the function mysqli_num_rows returns the count of records of a SELECT, you are doing an INSERT, to check if your record was inserted you can use mysqli_affected_rows this tells you if the record was inserted and also serves to make UPDATES. If you have your points with an AUTOINCREMENT field you can return the ID of the new record with mysqli_insert_id

<?php
    $con=mysqli_connect ('127.0.0.1','root','','freatico') or die ('ERROR EN LA CONEXION A LA BASE DE DATOS');
    $sql="INSERT INTO puntos VALUES ('".$_POST['idp']."','".$_POST['locali']."','".$_POST['ultmed']."','".$_POST['vref']."','".$_POST['altubo']."','".$_POST['sms']."')";
    $resultado=mysqli_query($con,$sql) or die ('ERROR EN EL QUERY DATABASE');
    if($resultado){
        if( mysqli_affected_rows($con) <= 0){
            echo 'EL PUNTO QUE ACABA DE REGISTRAR YA EXISTE';
    }

    else{
      echo mysqli_insert_id($con);
    }
}
    mysqli_close ($con);
?>
    
answered by 22.05.2018 / 17:28
source
0

You can do this.

<?php
        $con=mysqli_connect ('127.0.0.1','root','','freatico') or die ('ERROR EN LA CONEXION A LA BASE DE DATOS');
        $sql="INSERT INTO puntos VALUES ('".$_POST['idp']."','".$_POST['locali']."','".$_POST['ultmed']."','".$_POST['vref']."','".$_POST['altubo']."','".$_POST['sms']."')";
        $resultado=mysqli_query($con,$sql) or die ('ERROR EN EL QUERY DATABASE');
        if($resultado){
            if( mysqli_num_rows( $resultado )<=0){

                echo 'EL PUNTO QUE ACABA DE REGISTRAR YA EXISTE';
        }
    }
else {

echo"<script>alert('Error al insertar los datos')</script>";

}

        mysqli_close ($con);
    ?>
    
answered by 22.05.2018 в 17:26