How to fix "1452 > a Foreign key Constraint fails" error using PDO in PHP?

Asked

Viewed 10,272 times

2

First I know what is the mistake of Foreign key, however I do not know why it is happening in PHP code with 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 call of function

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

This is the error received:

Array ( [0] => 23000 [1] => 1452 [2] => Cannot add or update a 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 have checked the existence of cod_client, I have manually added to phpmyadmin and it worked.

  • There will be simple quotes in the interrogations! instead of (int)$id = $cod; would not be $id = (int) $cod;?

1 answer

4


The error happens because you try to insert a value that does not exist in the client table, because by adding simple quotes the placeholder(query) becomes a literal.

Change:

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

for:

INSERT INTO pedido (cod_cliente, data, pagamento, total) VALUES (?,?,?,?)
  • Wow, thank you so much, now that you corrected it, it made me look like a fool. Now I’m vaccinated!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.