PHP 之Mysql增删改查操作案例

1:user表:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

2:mysqltools.php  (mysql工具类)

php
    class MySqlTools{
    private $host='127.0.0.1';
    private $uname='root';
    private $pwd='mysql';
    private $dbname='test';
    
    private $conn;
    
    function __construct(){
        $this->conn=mysql_connect($this->host,$this->uname,$this->pwd)
        or die('mysql_connect error:'.mysql_error());
        mysql_select_db($this->dbname)
        or die('mysql_select_db error:'.mysql_error());
        mysql_query("set names 'utf8'");    
    }    

    function exec_dql($sql){
        $result=mysql_query($sql,$this->conn);
        $arr=array();
        while($row=mysql_fetch_assoc($result)){
        $arr[]=$row;
        }
        mysql_free_result($result);
        return $arr;
    }

    function exec_dml($sql){
        return mysql_query($sql,$this->conn);    
    }

    function free(){
        mysql_close($this->conn);    
    }
    }
?>

3:index.php  (首页)

PHP 之Mysql增删改查操作案例_第1张图片


    
    Index
    
    
    php
        require_once 'mysqltools.php';
        $mysql=new MySqlTools();
        $sql='select id,name from user';
        $users=$mysql->exec_dql($sql);    
    ?>
    php
        foreach($usersas$user){
        ?>
        
ID Name Oper
echo $user['id'];?> echo $user['name'];?> $user['id'];?>">详情 $user['id'];?>">删除

Add a new user

4:add.php  (增加新用户)

PHP 之Mysql增删改查操作案例_第2张图片


    
    Add
    
    

    
    

Add

Index
php if(!empty($_POST['uname'])){ $name=$_POST['uname']; require_once 'mysqltools.php'; $sql="insert into user(name) values('$name')"; $mysql=new MySqlTools(); if($mysql->exec_dml($sql)){ echo '

Add Success!

'; }else{ echo '

Add Error!

'; } } ?>
Name:

5:delete.php  (删除操作)

php
    $id=$_GET['id'];

    if(isset($id)){
    require_once 'mysqltools.php';
    $mysql=new MySqlTools();
    
    $sql="delete from user where id=$id";
    $mysql->exec_dml($sql);
    }

    header('Location: index.php');
?>

6:show.php  (显示详细信息页面)

PHP 之Mysql增删改查操作案例_第3张图片

php
    header('Conent-Type:text/html;charset=utf-8');

    $id=$_GET['id'];
    $name='';
    if(isset($id)){
    require_once 'mysqltools.php';
    $mysql=new MySqlTools();
    $sql="select name from user where id=$id limit 1";
    $arr=$mysql->exec_dql($sql);    
    $name=$arr[0]['name'];
    }

    echo "ID:$id
Name:$name
"; echo '

Index

'; ?>

 

 

你可能感兴趣的:(PHP 之Mysql增删改查操作案例)