mysql操作數據庫進行封裝實現增刪改查功能
阿新 • • 發佈:2018-04-22
mysqlSqlTool.class.php
<?php class SqlTool{ private $conn; private $host = "localhost"; private $user = "root"; private $password = "root"; private $db = "test1"; /* 連接數據庫的構造方法 */ function SqlTool(){ $this->conn = mysql_connect($this->host , $this->user , $this->password); if(!$this->conn){ die(‘連接失敗‘.mysql_error()); } mysql_select_db($this->db,$this->conn); mysql_query(‘set names gbk‘); } //select function execute_dql($sql){ $res = mysql_query($sql,$this->conn); return $res; } //insert、update、delete function execute_dml($sql){ $obj = mysql_query($sql,$this->conn); if(!$obj){ //return 0;//操作失敗 die(‘操作失敗‘.mysql_error()); }else{ if(mysql_affected_rows($this->conn)>0){ //return 1;//操作成功 echo "操作成功"; }else{ //return 2;//行數沒有收到影響 die(‘行數沒有受影響‘); } } } } ?>
SqlToolTest.php
<?php //引入數據庫類文件 require_once "SqlTool.class.php"; //----------------dml操作------------------ //插入 //$sql = "insert into user1(name , password , email , age) values(‘李四‘,md5(‘123‘),‘[email protected]‘,18)"; //刪除 //$sql = "delete from user1 where id = 9"; //更新 //$sql = "update user1 set id=4 where name=‘李四‘"; //創建一個SqlTool對象 //$SqlTool = new SqlTool(); //$res = $SqlTool->execute_dml($sql); //--------------------dql操作-------------------- $sql = "select * from user1"; //創建一個SqlTool對象 $SqlTool = new SqlTool(); $res = $SqlTool->execute_dql($sql); while($row=mysql_fetch_row($res)){ foreach($row as $key=>$val){ echo "--$val"; } echo "<br>"; } mysql_free_result($res); /*if($res==0){ die(‘操作失敗‘.mysql_error()); }else if($res==1){ echo "操作成功"; }else if($res==2){ echo "行數沒有受影響"; }*/ ?>
創建數據庫
create database test1;
創建數據表
create table user1(
id int auto_increment primary key,
name varchar(32) not null,
password varchar(64) not null,
email varchar(128) not null,
age tinyint unsigned not null
);
表結構
後續操作的圖片結果:
mysql操作數據庫進行封裝實現增刪改查功能