PDO: Insertion ne se fait pas
Bonjour et meilleurs voeux à tous.
J'ai une table vide avec la structure ci-dessous:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
DROP TABLE IF EXISTS `dat_books`;
CREATE TABLE IF NOT EXISTS `dat_books` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`title` varchar(50) NOT NULL,
`id_author` int(10) UNSIGNED DEFAULT NULL,
`id_publisher` int(10) UNSIGNED DEFAULT NULL,
`id_place` int(10) UNSIGNED DEFAULT NULL,
`id_public` int(10) UNSIGNED DEFAULT NULL,
`id_theme` int(10) UNSIGNED DEFAULT NULL,
`format` varchar(30) DEFAULT NULL,
`comment` text NOT NULL,
`update_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `id_auteur` (`id_author`),
KEY `id_editeur` (`id_publisher`),
KEY `id_place` (`id_place`),
KEY `id_theme` (`id_theme`),
KEY `id_public` (`id_public`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `dat_books`
ADD CONSTRAINT `dat_books_ibfk_1` FOREIGN KEY (`id_author`) REFERENCES `lst_authors` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT `dat_books_ibfk_2` FOREIGN KEY (`id_publisher`) REFERENCES `lst_publishers` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT `dat_books_ibfk_3` FOREIGN KEY (`id_place`) REFERENCES `lst_places` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT `dat_books_ibfk_4` FOREIGN KEY (`id_theme`) REFERENCES `lst_themes` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT `dat_books_ibfk_5` FOREIGN KEY (`id_public`) REFERENCES `lst_public` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
COMMIT; |
J'ai la fonction PDO suivante:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| function insertBook(array $data): false|string
{
$db = dbConnect();
extract($data);
var_dump($data);
$sql = <<<SQL
INSERT IGNORE INTO dat_books
(title, id_author, id_publisher, id_theme, id_public, id_place, format, comment)
VALUES(:title, :author, :publisher, :theme, :public, :place, :format, :comment)
SQL;
$params = [':title'=>$title, ':author'=>$author, ':publisher'=>$publisher, ':theme'=>$theme, ':public'=>$public, ':place'=>$place, ':format'=>$format, ':comment'=>$comment, ];
$stmt = $db->prepare($sql);
$stmt->execute($params);
return $db->lastInsertId(); // retourne 0
} |
Cette fonction ne renvoie aucune erreur MySQL.
La ligne 5 renvoie ceci:array (size=8)
'title' => string 'Coucou' (length=6)
'author' => string '1' (length=1)
'publisher' => string '1' (length=1)
'theme' => string '1' (length=1)
'public' => string '1' (length=1)
'place' => string '' (length=0)
'format' => string '' (length=0)
'comment' => string '' (length=0)
Bien que la table soit vide, l'insertion ne se fait pas mais l'auto_incrément augmente.
EDIT: Le mot clef IGNORE est important et j'ai ajouté une clef unique UNIQUE KEY `title` (`title`,`id_author`,`id_publisher`)