欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MySQL简单增删改查

程序员文章站 2022-03-03 17:42:00
...

前台页面例如


<form action="sql.php?action=insert" method="post">
  <input type="text" name="name" />
  <input type="text" name="pwd" />
  <input type="submit" value="Submit" />
</form>

后台操作


$action = $_GET['action']; //操作
switch = ('action'){
    case "select":
        $mysql = new pass();
        $mysqli=$mysql->db();
        $res = array();
        $hasList = false;
        $sql_select = "select id,name from user";
        if($result = $mysqli -> query($sql_select )){
            while($row = $result -> fetch_assoc()){
                $res[] = $row;
            }
            $result -> close();
        }
        if(!empty($res)){
            $hasList = true;
        }
        $arr = array(
                'code' => 1,
                'hasList' => $hasList,
                'count' => "5",
                'data' => $res,
            );
        echo json_encode($arr);
    break;

    case "insert":
        $mysql = new pass();
        $mysqli=$mysql->db();
        $res = array();
        $hasList = false;
        $sql_insert = "insert into user (name , pwd) values ('aidis' , '123')";
        if($mysqli -> query($sql_insert ) === true){
            echo = 1;
        }else{
            echo = 0;
        }
        $result -> close();
    break;

    case "update":
        $mysql = new pass();
        $mysqli=$mysql->db();
        $arr = $_POST;
        $id = $arr['id'];
        $name = $arr['name'];
        $pwd = $arr['pwd'];
        $sql_update = "update user set name = '$name' , pwd = '$pwd' where id = $id";
        if($mysqli -> query($sql_update ) === true){
            echo = 1;
        }else{
            echo = 0;
        }
        $result -> close();
    break;

    case "delete":
        $mysql = new pass();
        $mysqli=$mysql->db();
        $id = $_GET['id'];
        $sql_delete = "delete from user where id = $id";
        if($mysqli -> query($sql_delete ) === true){
            echo = 1;
        }else{
            echo = 0;
        }
        $result -> close();
    break;

}
class pass{
    function dbset(){
        $host='localhost';
        $user='root';
        $pass='password';
        $dbname='dbname';
        $mysqli=new mysqli($host,$user,$pass,$dbname);
        $mysqli->query('set names utf8');
        if ($mysqli->connect_errno) {
            printf("Connect failed: %s\n", $mysqli->connect_error);
            exit();
        }
        return $mysqli;
    }
    function db(){
        $mysqli=$this->dbset();
        return $mysqli;
    }
}
相关标签: PHP MYSQL