写法一:最简单的写法
header('Content-type:text/html; charset=utf8'); //连接数据库 $pdo = new PDO('mysql:dbname=test','root','root'); $sql = "DELETE FROM user WHERE id=3"; //方式一 if($pdo->exec($sql)==1){ echo '<h3 style="color:green">删除成功</h3>'; }else{ echo '<h3 style="color:red">删除失败</h3>'; }
写法二:使用try catch
header('Content-type:text/html; charset=utf8'); //连接数据库 $pdo = new PDO('mysql:dbname=test','root','root'); $sql = "DELETE FROM user WHERE id=3"; try{ if($pdo->exec($sql)==1){ echo '<h3 style="color:green">删除成功</h3>'; }else{ echo '<h3 style="color:red">没有数据被删除</h3>'; } }catch(PDOException $e){ echo '<h3 style="color:red">删除失败'.$e->getMessage().'</h3>'; }
写法三:先查询,再删除
header('Content-type:text/html; charset=utf8'); $pdo = new PDO('mysql:dbname=test','root','root'); $sqlr = "SELECT id,name,email FROM user WHERE id=37"; $pdo_stmt = $pdo->query($sqlr); if($pdo_stmt->rowCount()==1){ $row = $pdo_stmt->fetch(); $sqld = "DELETE FROM user WHERE id='{$row['id']}'"; if($pdo->exec($sqld)==1){ echo '<h3 style="color:green">删除成功</h3>'; }else{ echo '<h3 style="color:red">没有数据被删除</h3>'; } }else{ echo '<h3 style="color:red">没有找到数据,删除失败</h3>'; }