UniApp操作PHP连接MySql使用HASH加密注册会员及登录

注册

<template>
    <view class="page-container">
        <text class="title">会员注册</text>
        <input v-model="phone" placeholder="请输入手机号" />
        <input v-model="password" placeholder="请输入密码" type="password" />
        <button @click="register">注册</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                phone: '',
                password: ''
            };
        },
        methods: {
            register() {
				const crypto = require('crypto')
                if (!this.validatePhone(this.phone)) {
                    uni.showToast({
                        title: '请输入正确的手机号',
                        icon: 'none'
                    });
                    return;
                }
                if (this.password.length < 6) {
                    uni.showToast({
                        title: '密码长度不能少于6位',
                        icon: 'none'
                    });
                    return;
                }
                const registerData = {
                    action: 'register',
                    phone: this.phone,
                    password: crypto.createHash('sha1').update(this.password).digest('hex'),
                };
                uni.request({
                    url: 'http://localhost/api.php',
                    method: 'POST',
                    header: {
                        'Content-Type': 'application/json'
                    },
                    data: JSON.stringify(registerData),
                    success: (res) => {
                        if (res.data.code === 200) {
                            uni.showToast({
                                title: '注册成功',
                                icon: 'success'
                            });
                            // 注册成功后可根据需求跳转到登录页面或其他页面,这里示例跳转到登录页面
                            uni.navigateTo({
                                url: '/pages/login/login'
                            });
                        } else {
                            uni.showToast({
                                title: res.data.message,
                                icon: 'none'
                            });
                        }
                    },
                    fail: (err) => {
                        console.error('注册请求失败:', err);
                        uni.showToast({
                            title: '注册请求出错,请稍后重试',
                            icon: 'none'
                        });
                    }
                });
            },
            validatePhone(phone) {
                return /^1[3-9]\d{9}$/.test(phone);
            }
        }
    };
</script>

登录

<template>
    <view class="page-container">
        <text class="title">会员登录</text>
        <input v-model="phone" placeholder="请输入手机号" />
        <input v-model="password" placeholder="请输入密码" type="password" />
        <button @click="login">登录</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                phone: '',
                password: ''
            };
        },
        methods: {
            login() {
				const crypto = require('crypto')
                if (!this.validatePhone(this.phone)) {
                    uni.showToast({
                        title: '请输入正确的手机号',
                        icon: 'none'
                    });
                    return;
                }
                if (this.password.length < 6) {
                    uni.showToast({
                        title: '密码长度不能少于6位',
                        icon: 'none'
                    });
                    return;
                }
                const loginData = {
                    action: 'login',
                    phone: this.phone,
                    password: crypto.createHash('sha1').update(this.password).digest('hex'),
                };
                uni.request({
                    url: 'http://localhost/api.php',
                    method: 'POST',
                    header: {
                        'Content-Type': 'application/json'
                    },
                    data: JSON.stringify(loginData),
                    success: (res) => {
                        if (res.data.code === 200) {
                            uni.showToast({
                                title: '登录成功',
                                icon: 'success'
                            });
							uni.setStorageSync('token','fffffffffffffffasdfdsfdsfdsafa')
                            // 登录成功后可根据需求跳转到其他页面,比如会员中心页面等,这里可自行补充逻辑
                        } else {
                            uni.showToast({
                                title: res.data.message,
                                icon: 'none'
                            });
                        }
                    },
                    fail: (err) => {
                        console.error('登录请求失败:', err);
                        uni.showToast({
                            title: '登录请求出错,请稍后重试',
                            icon: 'none'
                        });
                    }
                });
            },
            validatePhone(phone) {
                return /^1[3-9]\d{9}$/.test(phone);
            }
        }
    };
</script>

AIP

<?php

header('Access-Control-Allow-Origin: http://localhost:8080');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

$servername = "localhost";
$username = "ygh";
$password = "******";
$dbname = "ygh";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("数据库连接失败: ". $conn->connect_error);
}

// 获取原始请求体数据
$jsonData = file_get_contents('php://input');
// 将JSON格式字符串解析为PHP数组
$data = json_decode($jsonData, true);

$action = isset($data['action'])? $data['action'] : '';
$phone = isset($data['phone'])? $data['phone'] : '';
$password = isset($data['password'])? $data['password'] : '';

switch ($action) {
    case'register':
        // 验证手机号是否已注册
        $checkStmt = $conn->prepare("SELECT COUNT(*) AS count FROM members WHERE phone =?");
        $checkStmt->bind_param("s", $phone);
        $checkStmt->execute();
        $checkStmt->bind_result($count);
        $checkStmt->fetch();
        $checkStmt->close();

        if ($count > 0) {
            $response = array(
                'code' => 400,
                'message' => '该手机号已注册,请直接登录'
            );
            echo json_encode($response);
            break;
        }

        // 插入新会员数据到数据库
        $insertStmt = $conn->prepare("INSERT INTO members (phone, password) VALUES (?,?)");
        $insertStmt->bind_param("ss", $phone, $password);
        if ($insertStmt->execute()) {
            $response = array(
                'code' => 200,
                'message' => '注册成功'
            );
        } else {
            $response = array(
                'code' => 500,
                'message' => '注册失败,请稍后重试'
            );
        }
        $insertStmt->close();
        echo json_encode($response);
        break;
    case 'login':
        // 查询数据库验证手机号和密码是否匹配
        $loginStmt = $conn->prepare("SELECT COUNT(*) AS count FROM members WHERE phone =? AND password =?");
        $loginStmt->bind_param("ss", $phone, $password);
        $loginStmt->execute();
        $loginStmt->bind_result($count);
        $loginStmt->fetch();
        $loginStmt->close();

        if ($count === 1) {
            $response = array(
                'code' => 200,
                'message' => '登录成功'
            );
        } else {
            $response = array(
                'code' => 401,
                'message' => '手机号或密码错误,请重新输入'
            );
        }
        echo json_encode($response);
        break;
    default:
        $response = array(
            'code' => 400,
            'message' => '无效的请求操作'
        );
        echo json_encode($response);
        break;
}

$conn->close();
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值