<?php //用PDO链接数据库PDO类 function conn(){ $dbh ='mysql:host=127.0.0.1;dbname=php;charset=utf8;port=3306;'; $dbuser='root'; $dbpwd='root'; try { $pdo = new PDO($dbh,$dbuser,$dbpwd); }catch (PDOException $e){ echo $e -> getMessage(); exit; } return $pdo; } //查询方法 //statement类 function select($colum="",$table,$condition="",$order="",$limit="") { $sql = ' SELECT '; //组装SQL语句 empty()函数判断是否为空 if (!empty($colum)){ $sql.= $colum ; }else{ $sql.= '*'; } $sql.= ' FROM '; $sql.=trim($table); if (!empty($condition)){ $sql.=' WHERE '; $sql.=$condition; } if(!empty($order)){ $sql.=' ORDER BY '.$order; } if(!empty($limit)){ $sql.=' LIMIT '.$limit; } $statem = conn()->prepare($sql); //预处理 $statem ->execute(); if (($statem ->rowCount()) >0){ //判断上条sql受影响行数,大于0表示找到了数据 由数据。 $statem ->setFetchMode( PDO::FETCH_ASSOC); //用索引数据返回结果。 return $statem ->fetchAll(); //拿到结果集 }else{ return false; } } //删除方法 function del($table,$condition){ $sql= " DELETE FROM "; //isset()判断变量由没由被定义(赋值) if (isset($table)){ $sql.=$table; }else{ $ech = "请传表名!"; return $ech; } if (isset($condition)){ $sql.=" WHERE "; $sql.=$condition; }else{ $ech = "请传条件!"; return $ech; } // echo $sql; //调试时使用 // exit; $statem = conn()->prepare($sql); $statem ->execute(); if (($statem ->rowCount()) >0){ $ech = "删除成功!!"; return $ech; }else{ return false; } } // $a = del("user","id=14"); // echo $a; //更新数据 function update($table,$colum,$column){ $sql = " UPDATE "; if (isset($table)){ $sql .=$table; }else { $ech = "必须要传表名"; return $ech; } if (isset($colum)){ $sql .=" SET ".$colum; }else { $ech = "必须要传需要更新的列名!"; return $ech; } if (isset($column)){ $sql .=" WHERE ".$column; }else { $ech = "需要找到哪条数据?!"; return $ech; } echo $sql; $statem = conn()->prepare($sql); $statem ->execute(); if (($statem ->rowCount()) >0){ $ech = "更新成功!!"; return $ech; }else{ return false; } } // $a = update("user","mobile=18373190150","id=16"); // echo $a; //插入数据 function insert($table,$varlue){ $sql=" INSERT INTO "; if (isset($table)){ $sql.=$table." "; }else{ $ech = "必须要传表名!!"; return $ech; } if (isset($varlue)){ $sql.=$varlue; }else{ $ech = "必须要传值!!"; return $ech; } // echo $sql; //调试时使用 $statem = conn()->prepare($sql); $statem ->execute(); if (($statem ->rowCount()) >0){ $ech = "添加成功!!"; return $ech; }else{ return false; } } // $a = insert("user(user_name,age,sex)","VALUES('liquanquan',18,1)"); // echo $a;
总结
通过本周的学习,了解了PDO的用法和类,学会了如何查询手册。通过方法封装常用代码块,在页面中不同位置调用。纯PHP代码可以不用?>闭环。对if语句有了新的认识。