将html数据传递到数据库

首先是一个用户可见的html网页

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>login</title>
</head>
<body>
<form action="result.php" method="post">
qq号码: <input type="text" name="username" ><br>
qq密码: <input type="text" name="password" ><br>
<input type="submit" value="登录">
</form>
</body>
</html>

这里写图片描述
点击登录后,将数据post给result.php

result.php

<?php
header("Content-type:text/html;charset=utf-8"); 
//数据类型是utf-8 不加入可能会乱码
    $serverName = "localhost";//服务器ip
    $username = "root";//mysql用户名称
    $password = "123456";//密码
    $dataBase = "yunhu";//数据库名称

    $conn = new mysqli($serverName, $username, $password,$dataBase);

    if($conn->connect_error) {//连接失败
        echo "对不起,服务器未响应";
        echo "<br>";
    }
    //数据库数据编码格式
    $sql = "SET NAMES UTF8";
    if($conn->query($sql) === true) {
        //echo "set success<br>";
    }
    else {
       echo "set fail<br>";
    }

    $username = $_POST['username'];
    $password = $_POST['password'];
    //echo $username." ".$password;
    $result = array();

    if($username == "") {
        $result["result"] = "false";
    }
    else {
        $add = $conn->prepare("INSERT INTO userInformation(username,password)  VALUES(?,?)");
        $add->bind_param("ss", $username,$password);

        $stmt = $conn->prepare("SELECT * FROM userInformation WHERE username=?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($id);


        if($stmt->fetch()) {
            $result["result"] = "false";
        }
        else {
            $add->execute();
            $result["result"] = "true";
        }
    }
    //echo json_encode($result);
?>
posted @ 2017-07-23 13:36  云胡同学  阅读(1662)  评论(0编辑  收藏  举报