PDO基于查询的更新操作
$dsn = "mysql:host=localhost;dbname=demo;charset=utf8"; $pdo = new PDO($dsn,'root','root'); $sql = "SELECT * FROM `user1` WHERE `id`=1"; try{ //只有读操作时才是用query执行生成结果集 $pdoStmt = $pdo->query($sql); //单独取出数据 // foreach ($pdoStmt as $row) //一次性取出所有数据 // $pdoStmt->fetchAll(); $row = $pdoStmt->fetch(); print_r($row); $data = ['name'=>'程序员']; $sql = "UPDATE `user1` SET `name`='{$data['name']}' WHERE `id`='{$row['id']}'"; if($pdo->exec($sql)){ echo '更新成功'; }else{ echo '更新失败'; echo '<pre>'; print_r($pdo->errorInfo()); } }catch(PDOException $e){ echo $e->getMessage(); }
PDO新增
$pdo = new PDO('mysql:dbname=demo','root','root'); $data = ['name'=>'小龙女','email'=>'xln@php.cn','password'=>'123456']; $sql = "INSERT user1 SET name='{$data['name']}',email='{$data['email']}',password='{$data['password']}'"; echo $pdo->exec($sql)? "新增成功":"新增失败";
PDO基于查询的删除操作
$dsn = "mysql:host=localhost;dbname=demo;charset=utf8"; $pdo = new PDO($dsn,'root','root'); $sql = 'SELECT * FROM user1 WHERE id=1'; $pdoStmt = $pdo->query($sql); $res = $pdoStmt->fetch(); $sql = "DELETE FROM user1 WHERE id='{$res['id']}'"; echo $pdo->exec($sql)? "删除成功":"删除失败";
总结:
一.PDO读写操作区别
读操作:1.通过 $pdo->query($sql) 执行; 2.执行后生成 $pdoStmt 对象 通过三种方式可取出
foreach($pdoStmt) $pdoStmt->feach() $pdoStmt->fetchAll();
写操作:1.通过 $pdo->exec($sql) 执行; 2.执行后返回布尔值
二、通用方法 $pdo->errorInfo() 输出错误信息 (非常实用)