0
votes

i have this problem :

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (tutoblog.post_category, CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES category (id) ON DELETE CASCADE ON UPDATE CASCADE)

1
public function attachCategories(int $id,array $categories){ $this->pdo->exec('DELETE FROM post_category WHERE post_id = ' . $id); $query= $this->pdo->prepare('INSERT INTO post_category SET post_id = ?,category_id = ?'); foreach ($categories as $category){ $query->execute([$id, $category]); } } - Mohamed Haouali
public function select(string $key, string $label, array $options = []): string { $optionsHTML = []; $value = $this->getValue($key); foreach ($options as $K => $v) { $selected = in_array($key,$value) ? " selected" : ""; $optionsHTML[] = "<option value=\"$key\"$selected>$v</option>" ; } $optionsHTML = implode('', $optionsHTML); return <<<HTML <div class="form-group"> <label for="field{$key}">{$label}</label> <select id="field{$key}" class="{$this->getInputClass($key)}" name="{$key}[]" required multiple>{$optionsHTML}</select> {$this->getErrorFeedback($key)} </div> HTML; - Mohamed Haouali

1 Answers

0
votes

You're trying to insert/update a table with a foreign key constraint.

The field category_id must be set to an id that exists in you table category. So make sure you create your category first and then link it in your entry.