Federick Jons Federick Jons - 5 months ago 18
SQL Question

Unhandled Exception. SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'idComplejo' cannot be null

when I open it, I have this error:


Unhandled Exception.
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'idComplejo' cannot be null


This is my php:

<?php

require("Db.class.php");


$db = new Db();

$response = array();


$idComplejo= $_POST['idComplejo'];
$idUsuario= $_POST['idUsuario'];


$result = $db->query("INSERT INTO baneo(idComplejo, idUsuario) VALUES(:idComplejo, :idUsuario)",
array("idComplejo" => $idComplejo, "idUsuario" => $idUsuario));

if($result == 0) {
$response["success"] = 0;
$response["mensaje"] = "Error";
}

else if($result > 0){
$response["success"] = 1;
$response["mensaje"] = "Success";
}

echo json_encode($response);
?>


Obviously, if I just open the php the variables are NULL. But I want to show this error if someone open this php:

$response["success"] = 0;
$response["mensaje"] = "Error";


The reason is because I want to secure my file and i don't want to show how my database looks like.

Thanks

Answer

Code needs some restructuring. Make sure you have values before attempting to insert as noted above

  <?php 

        require("Db.class.php");
        $db = new Db();
        $response = array(); //Not needed

        if(!empty($_POST['idComplejo']) && !empty($_POST['idUsuario'])){
              $idComplejo= $_POST['idComplejo'];
              $idUsuario= $_POST['idUsuario'];
        }else{
             $response["success"] = 0;
             $response["mensaje"] = "Error";
        }

        if(!isset($response["mensaje"])){
              //Required data is here
              $result = $db->query("INSERT INTO baneo(idComplejo, idUsuario)   VALUES(:idComplejo, :idUsuario)",array("idComplejo" => $idComplejo, "idUsuario" => $idUsuario));
       }


      if($result) { 
            $response["success"] = 1;
            $response["mensaje"] = "Success";
      }

      echo json_encode($response);

?>