我正在尝试将带有PDO的布尔值插入MySQLdatabase。如果$data['age2']
是false
,则不会进行插入,但是如果true
,则可以进行插入。如果我使用->bindParam()
方法,它将再次起作用。但是,如果有可能,我将在关联数组中传递变量。你知道我在做什么错吗?在代码的底部,我也插入了用于创建表的代码(我想插入到表中)。谢谢
<?php
$host = 'localhost';
$user = 'root';
$password = '12345';
$dbName = 'pdo';
// set DSN data sorce name
$dsn = "mysql:host={$host};dbname={$dbName}";
// create pdo instance
$pdoConn = new PDO($dsn, $user, $password);
$pdoConn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$data = [
':fname' => 'Bob',
':sname' => 'Desaunois',
':age' => '18',
':age2' => true
];
$sql = 'INSERT INTO posts (title, body, author, is_published) VALUES (:fname, :sname, :age, :age2)';
$statement = $pdoConn->prepare($sql);
$statement->execute($data);
/*
SHOW CREATE TABLE posts;
'posts', 'CREATE TABLE `posts` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `title` char(255) NOT NULL,\n `body` text NOT NULL,\n `author` char(255) NOT NULL,\n `is_published` tinyint(1) DEFAULT \'0\',\n `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB AUTO_INCREMENT=150 DEFAULT CHARSET=latin1'
posts, CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` char(255) NOT NULL,
`body` text NOT NULL,
`author` char(255) NOT NULL,
`is_published` tinyint(1) DEFAULT '0',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=150 DEFAULT CHARSET=latin1
*/