2020年6月2日
<?php
try{
$dsn="mysql:host=127.0.0.1;port=3306;dbname=liuyan;charset=utf8";
$pdo=new PDO($dsn,"root","root");
//准备sql语句
//$sql ="INSERT INTO books VALUES(2,'茄子',110)"; //增
//$sql="DELETE FROM books WHERE book_id=1"; //删
$sql="UPDATE books SET title='我起了一枪秒了'"; //改
$res=$pdo->exec($sql);
if($res){
echo "操作成功" .$res;
}else{
echo "操作失败";
}
$sql="SELECT * FROM books";
$res=$pdo->query($sql);
if($res){
echo"执行成功";
$fetch_data[];
while($row=$res->fetch(PDO::FETCH_ASSOC)){
$fetch_data[]=$row;
}
var_dump($fetch_data);
}else{
echo "执行失败";
}
}catch(PDDException $e){
var_dump($e->getMessage());
}
$sql="SELECT * FROM books";
$res=$pdo->query($sql);
if($res){
echo"执行成功";
$fetch_data[];
while($row=$res->fetch(PDO::FETCH_ASSOC)){
$fetch_data[]=$row;
}
var_dump($fetch_data);
}else{
echo "执行失败";
}
<?php
try{
$dsn="mysql:host=127.0.0.1;port=3306;dbname=liuyan;charset=utf8";
$pdo=new PDO($dsn,"root","root");
//准备sql语句
//$sql ="INSERT INTO books VALUES(2,'茄子',110)"; //增
//$sql="DELETE FROM books WHERE book_id=1"; //删
$sql="UPDATE books SET title='我起了一枪秒了'"; //改
$res=$pdo->exec($sql);
if($res){
echo "操作成功" .$res;
}else{
echo "操作失败";
}
$sql="SELECT * FROM books";
$res=$pdo->query($sql);
if($res){
echo"执行成功";
$fetch_data[];
while($row=$res->fetch(PDO::FETCH_ASSOC)){
$fetch_data[]=$row;
}
var_dump($fetch_data);
}else{
echo "执行失败";
}
}catch(PDDException $e){
var_dump($e->getMessage());
}
$sql="SELECT * FROM books";
$res=$pdo->query($sql);
if($res){
echo"执行成功";
$fetch_data[];
while($row=$res->fetch(PDO::FETCH_ASSOC)){
$fetch_data[]=$row;
}
var_dump($fetch_data);
}else{
echo "执行失败";
}
<?php
try{
$dsn="mysql:host=127.0.0.1;port=3306;dbname=liuyan;charset=utf8";
$pdo=new PDO($dsn,"root","root");
//准备sql语句
//$sql ="INSERT INTO books VALUES(2,'茄子',110)"; //增
//$sql="DELETE FROM books WHERE book_id=1"; //删
$sql="UPDATE books SET title='我起了一枪秒了'"; //改
$res=$pdo->exec($sql);
if($res){
echo "操作成功" .$res;
}else{
echo "操作失败";
}
$sql="SELECT * FROM books";
$res=$pdo->query($sql);
if($res){
echo"执行成功";
$fetch_data[];
while($row=$res->fetch(PDO::FETCH_ASSOC)){
$fetch_data[]=$row;
}
var_dump($fetch_data);
}else{
echo "执行失败";
}
}catch(PDDException $e){
var_dump($e->getMessage());
}
$sql="SELECT * FROM books";
$res=$pdo->query($sql);
if($res){
echo"执行成功";
$fetch_data[];
while($row=$res->fetch(PDO::FETCH_ASSOC)){
$fetch_data[]=$row;
}
var_dump($fetch_data);
}else{
echo "执行失败";
}
笔记
$dsn结构
每个结构用;分隔开
1.数据源名(myself)
2.安装地址(主机名)(host)
3.端口(port)默认3306
4.数据库名称(dbname)
5.编码(charset) 常用UTF8
PDO执行增删改操作
步骤:
1,准备sql语句
2,执行sql语句
当语句执行失败的时候回返回false;通常是语句写错了或者是表名写错了
结果类别
PDO::FETCH_ASSOC 结果设置未关联数组
PDO::FETCH_BOTH 结果只为混合数组
PDO::FETCH_NUM 结果只为索引数组