1.pdo连接
<?php /* * PDO:PHP Data Object * 作用:对PHP提供了一个统一的访问接口,屏蔽了各数据库的差异 * 优点:迁移数据库友好,高效,统一 */ //print phpinfo(); //查看有没有配置pdo文件 //1.连接规范语法 header('content-type:text/html;charset=utf-8'); $dsn = 'mysql:host=localhost; dbname=demo1;charset=utf8'; $userName = 'root'; $password = 'root'; try { $pdo = new PDO($dsn,$userName,$password); }catch (PDOException $e) { die('connect ERROR:'.$e->getMessage()); } //简单写法 //$pdo = new PDO('mysql:dbname=demo1','root','root') or die();
2.select操作
<?php require 'inc/pdo_connect.php'; //准备sql语句 $sql = "SELECT `id`,`name`, `email` FROM `userLog` WHERE `id`>5 "; //执行查询,并将结果集传到$pdoStmt $pdoStmt = $pdo->query($sql); try { echo '<h3 align="center">用户信息表</h3>'; echo '<table align="center" cellspacing="0" border="1" cellpadding="5">'; echo '<tr bgcolor="#87ceeb"><th>ID</th><th>NAME</th><th>EMAIL</th></tr>'; while ($row = $pdoStmt->fetch()) //从结果集中循环抓取数据 { echo '<tr align="center">'; echo '<td>'.$row['id'].'</td><td>'.$row['name'].'</td><td>'.$row['email'].'</td>'; echo '</tr>'; } echo '</table>'; echo '<h3 align="center">输出了'.$pdoStmt->rowCount().'条数据</h3>'; }catch (PDOException $e) { echo $e->getMessage(); } unset($pdo);
3.update操作
<?php require 'inc/pdo_connect.php'; //准备sql语句 $sql = "SELECT * FROM `userLog` WHERE `name`='杨过' "; //执行查询,并将结果集传到$pdoStmt $pdoStmt = $pdo->query($sql); if ($pdoStmt->rowCount()== 1) { //准备更新语句,记住如果忘记where会将所有的都更新 $sql1="UPDATE `userLog` SET `email`='yg123@php.cn' WHERE `name`='杨过'"; //执行该语句 $num = $pdo->exec($sql1); try { if ($num == 1) { echo '更新成功'; }else { echo '没有更新'; } }catch (PDOException $e) { echo $e->getMessage(); } }else { echo '没有找到更新语句'; } //销毁 unset($pdo);
4.insert操作
<?php require 'inc/pdo_connect.php'; //准备插入数据 $data = ['name'=>'风清扬','email'=>'fqy@php.cn','psd'=>'678']; //sql插入语句 $sql = "INSERT `userLog` SET `name`='{$data['name']}',`email`='{$data['email']}',`psd`=sha1('{$data['psd']}')"; //执行sql语句 $num = $pdo->exec($sql); if ($num == 1) { echo '新增1条数据,新增的id为 '.$pdo->lastInsertId(); }else { echo '新增失败<br>'; print_r($pdo->errorInfo()); } //销毁pdo数据 unset($pdo);
5.删除操作
<?php require 'inc/pdo_connect.php'; //准备sql语句 $sql = "SELECT * FROM `userLog` WHERE `name`='杨过' "; //执行查询,并将结果集传到$pdoStmt $pdoStmt = $pdo->query($sql); if ($pdoStmt->rowCount()== 1) { //准备删除语句, $sql1="DELETE FROM `userLog` WHERE `name`='杨过' "; //执行该语句 $num = $pdo->exec($sql1); try { if ($num == 1) { echo '删除成功'; }else { echo '未找到删除记录'; } }catch (PDOException $e) { echo $e->getMessage(); } }else { echo '没有找到要删除的语句'; } //销毁 unset($pdo);
读操作$pdo->query()
写操作$pdo->exec()