PHP没有将适当的数据传递给MYSQL

时间:2018-10-19 13:57:04

标签: php html mysql post mysqli

我无法将适当的数据传递给MySQL,我不知道我做错了什么,请帮助我,我的代码如下:

$con = mysqli_connect('localhost', 'root', '', 'database');
if($con) {
    echo "we are connected";
} else {
    die("connection failed");
}

if(isset($_POST['submit'])) {

    // echo "Yeah it works";
    $user = $_POST['username'];
    $pass = $_POST['password'];

    $query = "INSERT INTO users(username, password) VALUES ('$user', '$pass')";
    $result = mysqli_query($con, $query);

    if(!$result) {
        die("Query failed");
    }
}

运行此代码时,我得到0的{​​{1}}和username的{​​{1}}。无论我为0password输入什么,我都会在数据库中得到usernameenter image description here

1 个答案:

答案 0 :(得分:2)

尝试使用此代码,该代码还会删除SQL injections

$con = mysqli_connect('localhost', 'root', '', 'database');

if(! $con )
    die('Unable to connect');

foreach(array('submit', 'username', 'password') as $arg)
    if(! isset($_POST[$arg]) )
        die('Missing argument(s)');

unset($arg);
http_response_code(200);

$username = $con->real_escape_string($_POST['username']);
$password = $con->real_escape_string($_POST['password']);

$query = "INSERT INTO users (username, password) VALUES ('{$username}', '{$password}')";
if(! mysqli_query($con, $query))
    http_response_code(400);

如果此代码不起作用,请确保表中的用户名密码 varchar的而不是 int的。 (因为您的脚本插入了 0 值)