PDO 如何连接
new PDO("mysql:host=localhost;dbname=php100","root", “ ");
默认这个不是长连接,如果需要数据库长连接,需要最后加一个参数:
array(PDO::ATTR_PERSISTENT => true) 变成这样:
new PDO(“连接信息”, ‘root‘, ‘‘, array(PDO::ATTR_PERSISTENT => true));
PDO 常用方法及其使用
PDO::query() 主要是用于有记录结果返回的操作,特别是SELECT操作
PDO::exec() 主要是针对没有结果集合返回的操作,如INSERT、UPDATE等操作
PDO::lastInsertId() 返回上次插入操作,主键列类型是自增的最后的自增ID
PDOStatement::fetch() 是用来获取一条记录
PDOStatement::fetchAll() 是获取所有记录集到一个中
<?php
$pdo=new PDO("mysql:host=localhost;dbname=php100","root","");
$pdo->exec("insert into `php100`(`id`,`name`,`hit`)values(‘‘,‘PHP200‘,‘5‘)");
$pdo->query("select * from `php100` limit 0,2");
$row=$sr->fetchAll();
print_r($row);
?>
$pdo=new PDO("mysql:host=localhost;dbname=php100","root","");
$pdo->exec("insert into `php100`(`id`,`name`,`hit`)values(‘‘,‘PHP200‘,‘5‘)");
$pdo->query("select * from `php100` limit 0,2");
$row=$sr->fetchAll();
print_r($row);
?>
实例
<?php
$pdo=new PDO("mysql:host=localhost;dbname=php100","root","");
$pdo->exec("insert into `php100`(`id`,`name`,`hit`)values(‘‘,‘PHP200‘,‘5‘)");
$pdo->query("select * from `php100` limit 0,2");
$row=$sr->fetchAll();
print_r($row);
?>
$pdo=new PDO("mysql:host=localhost;dbname=php100","root","");
$pdo->exec("insert into `php100`(`id`,`name`,`hit`)values(‘‘,‘PHP200‘,‘5‘)");
$pdo->query("select * from `php100` limit 0,2");
$row=$sr->fetchAll();
print_r($row);
?>
<?php
$pdo=new PDO("mysql:host=localhost;dbname=php100","root","");
$pdo->exec("insert into `php100`(`id`,`name`,`hit`)values(‘‘,‘PHP200‘,‘5‘)");
$sr=$pdo->query("select * from `php100`");
while($row=$sr->fetch())
print_r ($row);
?>
$pdo=new PDO("mysql:host=localhost;dbname=php100","root","");
$pdo->exec("insert into `php100`(`id`,`name`,`hit`)values(‘‘,‘PHP200‘,‘5‘)");
$sr=$pdo->query("select * from `php100`");
while($row=$sr->fetch())
print_r ($row);
?>