创建一个数据库 php_course
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for posts
-- ----------------------------
DROP TABLE IF EXISTS `posts`;
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`content` text,
KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
插入数据库
try{
$db_handle = new PDO('mysql:host=localhost;dbname=php_course;charset=utf8','root','');
$statement = $db_handle->prepare('INSERT INTO posts(title,content) VALUES (:title,:content)');
$data = array(
'title' => '海上钢琴师',
'content' => '一名具有钢琴天赋的孤儿历经一切的苦难'
);
$statement->execute($data);
}catch(PODException $e){
echo $e->getMessage();
}
查找数据
try{
$db_handle = new PDO('mysql:host=localhost;dbname=php_course;charset=utf8','root','');
$statement = $db_handle->prepare('SELECT * FROM posts');
$statement->execute();
$statement->setFetchMode(PDO::FETCH_ASSOC);
while($row = $statement->fetch()){
echo '《' .$row['title'] . '》' . $row['content'] .'
';
}
}catch(PODException $e){
echo $e->getMessage();
}