对于数据库的连接方式有很多种,其中pdo对php的支持性是最好的.
对于pdo连接数据库,和增删改查.查询所有数据的时候一定要用count(*)来求的总的行数才可以获取到正确的记录数.
以下是我的代码.,
实例
<?php //用数组创建连接数据库的内容 $db=['sql'=>'mysql:host=127.0.0.1;dbname=php','user'=>'root','password'=>'root']; try { //创建一个pdo对象连接数据库,判断数据库是否连接成功 $pdo = new PDO($db['sql'], $db['user'], $db['password']); // echo '<h2>连接成功</h2>'; //返回错误信息 } catch (PDOException $a) { die('连接失败 :'. $a->getMessage()); } echo "<hr>"; echo "<h3>新增数据</h3>"; //准备SQL语句,用"命名占位符" $sql1 = "INSERT IGNORE `staff` SET `name`= :name ,`age` = :age , `salary` =:salary "; //创建预处理对象 $stmt1 = $pdo->prepare($sql1); //创建参数数组 $data1 = ['name'=>'杨过1','age'=>25,'salary'=>8000]; //传入参数 if ($stmt1->execute($data1)) { if ($stmt1->rowCount()>0) echo '<h3>成功添加了'.$stmt1->rowCount().'条记录</h3>'; } else { echo '<h3>添加失败</h3>'; print_r($stmt1->errorInfo()); exit(); } echo "<hr>"; echo "<h3>更新数据</h3>"; $sql2 = "UPDATE `staff` SET `salary` =:salary WHERE `id`> :id "; $stmt2 = $pdo->prepare($sql2); $data2 = ['id'=>6,'salary'=>8000]; if ($stmt2->execute($data2)) { // rowCount(): 返回受影响的记录数量 echo '<h3>成功更新了'.$stmt2->rowCount().'条记录</h3>'; } else { echo '<h3>更新失败</h3>'; print_r($stmt2->errorInfo()); exit(); } echo "<hr>"; echo "<h3>删除数据</h3>"; $sql3="DELETE FROM `staff` WHERE `id`> :id"; $stmt3 = $pdo->prepare($sql3); $data3 = ['id'=>16]; if ($stmt3->execute($data3)) { echo '<h3>成功删除了' . $stmt3->rowCount() . '条记录</h3>'; }else { echo '<h3>删除失败</h3>'; print_r($stmt3->errorInfo()); exit(); } echo "<hr>"; echo "<h3>查询数据</h3>"; $sql4= "select count(*) from `staff` where `salary` > :salary"; $stmt4 = $pdo->prepare($sql4); $data4 = ['salary'=>9000]; if ($stmt4->execute($data4)) { echo "<h3>查询到工资大于{$data4['salary']}的人数是" . $stmt4->fetchColumn() . '个</h3>'; } else { echo '<h3>查询失败</h3>'; print_r($stmt4->errorInfo()); exit(); } // 关闭连接 $stmt = null; ?>
运行实例 »
点击 "运行实例" 按钮查看在线实例