douyu5775 2016-05-23 12:02
浏览 35
已采纳

如何从php表单成功查询MySql服务器? [重复]

This question already has an answer here:

This is my existing code:

<?php
include('config.php');
session_start();
if(isset($_POST['submit'])) {
  if(!$_POST['username']) {
    $error['username'] = "<p>Please supply your name.</p>
";
  }
  if(!$_POST['password']) {
    $error['password'] = "<p>Please supply your password.</p>
";
  }

  if(!is_array($error)) {       
        $db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

        if($db === false) {
            die('Could not connect: ' . mysqli_error());
        }

        $user = mysqli_real_escape_string($db, $_POST['username']);
        $pass = mysqli_real_escape_string($db, password_hash($_POST['password'], PASSWORD_BCRYPT));

        $query = "INSERT INTO users (USERNAME, PASSWORD) VALUES ('$user', '$pass')";
        mysqli_query($query, $db);

        mysqli_close($db);
  }
}
?>

This just doesn't seem to work. The connection is fine because I am using the same process in another file and it works perfectly. I just wondered why the query isn't doing anything?

EDIT:

Here's the form and changed to mysqli in above:

<html>

<head>
    <title>Add Users</title>
</head>

<body>

    <form method="post" action="formProcess.php">
        Username: <input type="text" name="username"><br> Password: <input type="password" name="password"><br>
        <input type="submit">
    </form>
</body>

</html>
</div>
  • 写回答

2条回答 默认 最新

  • doucang6739 2016-05-23 12:10
    关注

    You need to use either mysql_* or mysqli_* functions throughout your whole script. Use the latter as mysql_* functions has been deprecated.

    Edited code:

    mysqli_query($db, $query);
    
    mysqli_close($db);
    

    The parameters required for mysqli_query is connection followed by query.

    More information at http://php.net/manual/en/mysqli.query.php.


    Also, you need to specify the name attribute in your submit button:

    <input name="submit" type="submit">
    

    Thanks to @Fred-ii- for the hint!


    Just a tip: You shouldn't store users' passwords as plain-text, you should hash/ crypt it.

    In PHP 5.5, there's a Password Hash function: http://php.net/manual/en/ref.password.php.

    Also, you shouldn't escape the password before hashing as it would change the hash since slashes will be added.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题