php可以通过三种方式操作数据库,分别用mysql扩展库,mysqli扩展库,和mysqli的预处理模式分别举案例加以说明
1.通过mysql方式操作数据库
工具类核心代码:
conn = mysql_connect($this->host,$this->username,$this->password);if(!$this->conn){die("数据库链接失败".mysql_error());}//选择数据库mysql_select_db("test") or die("数据库不存在".mysql_error()) ;//设置编码mysql_set_charset ( "utf8",$this->conn);//mysql_query("set names utf8");}function execute_dql($sql){$res = mysql_query($sql,$this->conn);if(!$res){die("数据查询失败");}else{return $res;}}function execute_dml($sql){$res = mysql_query($sql,$this->conn);if(!$res){echo mysql_error();return -1;}else{if(mysql_affected_rows($this->conn)>0){return 1;}else{return 0;}}}}?>
2.通过mysqli扩展库操作mysql
工具类核心代码:
host,$this->username,$this->password,$this->db);if(self::$mysqli->connect_error){die("数据库连接失败".self::$mysqli->connect_error);}//设置编码self::$mysqli->set_charset("utf8");}function execute_dql($sql){$res = self::$mysqli->query($sql);return $res;}function queryfiledname($sql){$filedname = self::$mysqli->query($sql);return $filedname;}function execute_dml($sql){$b = self::$mysqli->query($sql);if(!$b){return -1;}else{if(self::$mysqli->affected_rows>0){return 1;}else{return 0;}}}}?>
3.mysqli扩展库的预处理方式
处理dml语句:
query("SET NAMES utf8");//数据库预处理$mysqli_stmt = $mysqli->prepare($sql) or die("数据库预处理失败");//绑定参数$name="小倩";$password = "123";$email = "xiaoqian@suhu.com";$address = "郑州";$age = 20;$mysqli_stmt->bind_param("ssssi",$name,$password,$email,$address,$age) or die("绑定参数失败");//执行$b = $mysqli_stmt->execute();if(!$b){die("预处理执行失败");}echo "添加成功";$mysqli_stmt->close();?>处理dql语句: query("set names utf8");$sql="select * from user where id>?";$mysqli_stmt = $mysqli->prepare($sql) or die("数据库预处理失败");$id=20;$mysqli_stmt->bind_param("i",$id) or die("参数绑定失败");$mysqli_stmt->bind_result($id,$username,$password,$email,$address,$age) or ("绑定结果集失败");$b = $mysqli_stmt->execute();if(!$b){die("数据库预处操作理失败");}while($mysqli_stmt->fetch()){echo "--$id--$username";}$mysqli_stmt->free_result();$mysqli_stmt->close();$mysqli->close();?>