How to fix the "1452 foreign key constraint fails" error using PDO in PHP?

1

Firstly I know what the foreign key error is, however I do not know why it is happening in PHP code with the PDO.

  

Insertion Function:

function insert_pedido($cod,$pagamento,$total){

    (int)$id = $cod;

    $con = $this->connect();

    $data = date("Y/m/d");

    $DBH = $con->prepare("INSERT INTO pedido (cod_cliente, data, pagamento, total) VALUES ('?','?','?','?')");
    $DBH->bindParam(1,$id);
    $DBH->bindParam(2,$data);
    $DBH->bindParam(3,$pagamento);
    $DBH->bindParam(4,$total);
    if($DBH->execute()){

        return 1;

    }else{

        print_r($DBH->errorInfo());

    }

}
  

I call the function by passing these parameters

$cod = $_POST["cod_cliente"];
$pagamento = $_POST["pagamento"];
$total = $_POST["total"];

And the function call

insert_pedido($cod,$pagamento,$total);

This is the error you received:

Array ( => 23000 [1] => 1452 [2] => Can not add or update child row: a foreign key constraint fails ( empresa . pedido , CONSTRAINT fk_cliente FOREIGN KEY ( cod_cliente ) REFERENCES cliente ( cod_cliente ) ON DELETE NO ACTION ON UPDATE NO ACTION))

  

As I said before, I already checked the existence of the client_client, I already manually added it to phpmyadmin and it worked.

    
asked by anonymous 02.03.2016 / 19:51

1 answer

2

The error happens because you try to insert a value that does not exist in the client table, because when adding single quotation marks the placeholder turns into a literal.

Change:

INSERT INTO pedido (cod_cliente, data, pagamento, total) VALUES ('?','?','?','?')

To:

INSERT INTO pedido (cod_cliente, data, pagamento, total) VALUES (?,?,?,?)
    
02.03.2016 / 19:58