PDO实现用户数据的增删改查
1.三种PDO的连接数据库的方法:<?php//$mysqli=new mysqli("localhost","user","password","dbname");//PDO对象初始化try{//3种PDO的连接数据库方法//1. $pdo=new PDO("mysql:host=localhost;dbname=myapp","root","");//2
·
为什么要用PDO?
答:避免因项目更换数据库而造成大量重复劳动的SQL语句重写
PDO对象成员方法主要有哪些?
1.三种PDO的连接数据库的方法:
<?php
//$mysqli=new mysqli("localhost","user","password","dbname");
//PDO对象初始化
try{
//3种PDO的连接数据库方法
//1. $pdo=new PDO("mysql:host=localhost;dbname=myapp","root","");
//2. $pdo=new PDO("uri:mysqlPdo.ini","root","");
//3. $pdo=new PDO("mysqlpdo","root","");
$pdo=new PDO("mysqlpdo","root","");
}catch (PDOException $e){
die("fail to connect db".$e->getMessage());
}
//查看属性
$attributes = array(
"AUTOCOMMIT" , "ERRMODE" , "CASE" , "CLIENT_VERSION" , "CONNECTION_STATUS" ,
"ORACLE_NULLS" , "PERSISTENT" , "PREFETCH" , "SERVER_INFO" , "SERVER_VERSION" ,
"TIMEOUT"
);
foreach ( $attributes as $val ) {
echo "PDO::ATTR_ $val : " ;
echo $pdo ->getAttribute ( constant ( "PDO::ATTR_ $val " ))."<br/>" ;
}
//print_r($pdo);
2.PDO实现数据库的增删改查:
<?php
/**
* 查询数据
*/
//1.连接数据库
try{
$pdo=new PDO("mysql:host=localhost;dbname=myapp","root","");
}catch (PDOException $e){
die("fail to connect mysql".$e->getMessage());
}
//print_r($pdo);
//2.执行query(查询)返回一个预处理对象,使用快捷方式
$sql="SELECT * FROM users";
foreach($pdo->query($sql) as $val){
echo $val['id']."------".$val['name']."------".$val['age']."<br/>";
}
/**
* 添加数据
*/
//$sql="INSERT INTO users VALUES(null,'Susan','29')";
/**
* 更新数据
*/
//$sql="UPDATE users set name='Kill' WHERE id=1";
/**
* 删除数据
*/
$sql="DELETE FROM users WHERE id=8";
$res=$pdo->exec($sql);
if($res){
echo "success";
}
更多推荐
已为社区贡献1条内容
所有评论(0)