PHP MySQL基本操作之增删改查

本文针对前端小伙伴,以最简单化的方式实现增删改查(真后台的小伙伴不要吐槽)。假设您已经安装好了wamp集成环境,正好还懂那么点php,另外还假设您已经知道如何创建数据库,数据表。
这里以面向对象的MySQLi (面向对象)技术来实现。

MySQL基本语句模板

SELECT * FROM student WHERE status="1" //查询语句,查询数据表student中学生用户状态为1的学生的所有信息
SELECT name, password, login_time FROM student WHERE  status="1" //查询语句,查询数据表student中学生用户状态为1的学生的部分信息(姓名,密码,登录时间)
INSERT INTO student (name, password, login_time, status) VALUES ("张三丰","m123456","2018-01-11","1") //插值语句,增加一条学生信息
UPDATE student SET password="888888",login_time="2018-01-12" WHERE name="张三丰" AND status="1" //修改语句,修改学生“张三丰”的密码及登录时间
DELETE FROM student WHERE name="张无忌" //删除语句,删除学生“张无忌”的学生信息

PHP MySQL连接数据库操作

dbConfig.php文件

php
header('Content-type:text/html;charset=utf-8');//设置编码格式
define('SERVER', 'localhost');//wamp集成环境下默认主机名为localhost
define('USER', 'root');//wamp集成环境下默认用户名为root
define('PSW', '');//wamp集成环境下密码默认为空,放空引号即可
define('DB', 'school');//school为数据库名称
// 创建连接
$link = new mysqli(SERVER, USER, PSW, DB);
// 检测连接
if ($link->connect_error) {
    die("连接失败: " . $link->connect_error); //连接失败,抛出异常
}
// 修改数据库连接字符集为 utf8
mysqli_set_charset($link, "utf8"); //如果您想存入中文的话,必须设置

PHP MySQL 增加数据操作


header('Content-type:text/html;charset=utf-8');//设置编码格式
include_once 'dbConfig.php'; //引入dbConfig.php文件,获得连接数据库功能对象$link

$user = '张三丰'; //虚拟数据,通常来自于前端
$psw = '123456';//虚拟数据,通常来自于前端

$psw = md5($psw); //对密码进行md5加密
$addTime = time() * 1000; //存入当前时间毫秒数
//sql语句
$insertSql = 'INSERT INTO student (name, password, login_time) VALUES ("' . $user . '","' . $psw . '","' . $addTime . '")';
if ($link->query($insertSql) === true) {
    $response = ['status' => 1, 'msg' => '注册成功。'];
    response($response);
} else {
    $response = ['status' => 0, 'msg' => '创建失败!'];
    response($response);
}
function response($msg)
{
     
    echo json_encode($msg);//输出json字符串
    exit();//终止任务
}

$link->close();//关闭数据库连接
?>

PHP MySQL 删除数据操作


header('Content-type:text/html;charset=utf-8');//设置编码格式
include_once 'dbConfig.php'; //引入dbConfig.php文件,获得连接数据库功能对象$link

$user = '张三丰'; //虚拟数据,通常来自于前端
//方法一:直接删除数据表中的数据
$deleteSql = 'DELETE FROM student where name="' . $user . '"';
//方法二:只是修改数据表中该用户的状态,比如修改状态status=0
$updateSql = 'UPDATE student SET status="0"';

if ($link->query($deleteSql) === true) {
    $response = ['status' => 1, 'msg' => '成功删除。'];
    response($response);
}
function response($msg)
{
      
    echo json_encode($msg);//输出json字符串
    exit();//终止任务
}

$link->close();//关闭数据库连接
?>

PHP MySQL 修改数据操作


header('Content-type:text/html;charset=utf-8');//设置编码格式
include_once 'dbConfig.php'; //引入dbConfig.php文件,获得连接数据库功能对象$link

$user = '张三丰'; //虚拟数据,通常来自于前端

//这其实也是一种删除方式:只是修改数据表中该用户的状态,比如修改状态为status=0表示不可用
$updateSql = 'UPDATE student SET status="0" WHERE name="' . $user . '"';

if ($link->query($updateSql) === true) {
    $response = ['status' => 1, 'msg' => '修改成功。'];
    response($response);
}
function response($msg)
{
     
    echo json_encode($msg);//输出json字符串
    exit();//终止任务
}

$link->close();//关闭数据库连接
?>
PHP MySQL 查询数据操作

header('Content-type:text/html;charset=utf-8');//设置编码格式
include_once 'dbConfig.php'; //引入dbConfig.php文件,获得连接数据库功能对象$link

$selectStudent = 'SELECT * FROM student WHERE status="1"'; //查询语句,查询可用的学生账号

$result = $link->query($selectStudent);
if ($result->num_rows > 0) {
    $rows = [];//定义空数组作为接收对象
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    response($rows);//输出结果
}
$link->close();//关闭数据库;

function response($msg)
{
      
    echo json_encode($msg);
    exit();
}

?>

完整案例

jQuery+html+ajax+php实现最简单的注册

需要事先配制好数据库,效果图如下

PHP MySQL基本操作之增删改查_第1张图片

html代码

<html lang="en">
<head><meta charset="UTF-8"><title>logintitle>head>
<body>
<form action="#" id="login">
    <label for="user">用户名:label><input type="text" id="user" name="user"><br>
    <label for="psw">密码:label><input type="password" id="psw" name="psw"><br>
    <input type="submit" id="sub" value="注册">
form>

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js">script>
<script>
    $(function () {
      
        var sub = $('#sub');
        sub.click(function (e) {
      
            e.preventDefault();
            var datas = $('#login').serialize();
            datas = unserialize(datas);
            $.ajax({
                type: 'post',
                url: './admin/register.php',
                data: datas,
                dataType: 'json',
                success: function (response) {
      
                    console.log(response);//打印后台返回结果
                }
            })
        });
        //反序列化,将字符串转换成json对象
        function unserialize(datas) {
      
            datas = datas.split('&');
            var obj = {};
            datas.forEach(function (item) {
      
                var key = item.split('=')[0];
                obj[key] = item.split('=')[1];
            });
            return obj;
        }
    })
script>
body>html>

php代码(dbConfig.php与文章开头的一致)


header('Content-type:text/html;charset=utf-8');
include_once 'dbConfig.php';
if ($_POST) {
    $user = urldecode($_POST['user']);//提交过来的中文会被utf-8编码,需要urldecode解码为中文
    $psw = $_POST['psw'];
    if (!$user) {
        $response = ['status' => 0, 'msg' => '用户名不能为空!'];
        response($response);
    } else {
        $regu = '/^([^\x{00}-\x{ff}]|\w){2,16}$/u';//php正则匹配中文及字母数字下划线等等
        if (!preg_match($regu, $user)) {
            $response = ['status' => 0, 'msg' => '用户名只能是字母数字下划线,且长度为2-16。'];
            response($response);
        }
    }
    if (!$psw) {
        $response = ['status' => 0, 'msg' => '密码不能为空!'];
        response($response);
    } else {
        $regp = '/^\w{6,16}$/';//php正则匹配简单的密码
        if (!preg_match($regp, $psw)) {
            $response = ['status' => 0, 'msg' => '密码只能是字母数字下划线,且长度为6-16。'];
            response($response);
        }
    }

    $time = time() * 1000;//将时间戳改为毫秒数
    $psw = md5($psw);//md5加密密码,避免出现源密码
    $selectStudent = 'SELECT * FROM student WHERE name="' . $user . '"';
    $insertStudent = 'INSERT INTO student (name, password, login_time) VALUES ("' . $user . '","' . $psw . '","' . $time . '")';
    $result = $link->query($selectStudent);//执行MySQL语句
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $response = ['status' => 0, 'msg' => $row['name'] . '已经被注册过了!'];
            response($response);
        }
    }
    if ($link->query($insertStudent) === true) {
        $response = ['status' => 1, 'msg' => '注册成功。'];
        response($response);
    } else {
        $response = ['status' => 0, 'msg' => '创建失败!'];
        response($insertStudent);
    }
}
$link->close();//关闭数据库;

function response($msg)
{
     
    echo json_encode($msg); //转换成json字符串输出到前端
    exit();//终止任务
}

?>

你可能感兴趣的:(web基础,MySQL,增删改查,CRUD)