php入门pdo的使用--增加数据,查询数据
2017-03-30 本文已影响10人
snakeSkin
<?php
try{
//$dsn 数据库驱动,
$dsn = "mysql:dbname=classphp;host=127.0.0.1";
$name = "root";
$pwd = "";
$pdo = new PDO($dsn,$name,$pwd);
//设置错误处理模式,推荐为异常处理模式
$pdo -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
echo $pdo -> getAttribute(PDO::ATTR_ERRMODE);
$username = "jixue";
$pwd = md5(12345);
$email = "18868831752@163.com";
$sql = "INSERT INTO PERSON(username,pwd,email) VALUE('{$username}','{$pwd}','{$email}')";
//exec只执行有影响行数的语句(通常指增,删,改)
$affected = $pdo -> exec($sql);
//query执行有结果集的语句 (通常指查询)
$sql = "SELECT * FROM PERSON";
$stmt = $pdo -> query($sql);
var_dump($stmt);
echo "<hr/>";
var_dump($affected);
echo "<hr/>";
foreach ($stmt as $key ) {
echo "{$key['id']}-{$key['username']}-{$key['pwd']}-{$key['email']}-<br/>";
}
// var_dump($pdo);
}
catch(PDOException $e){
echo $e -> getMessage();
echo $e -> getFile();
echo $e -> getLine();
echo $e -> getCode();
}
?>
执行后页面显示:
上面代码打印输出