将PHP表单添加到SQL数据库

时间:2016-11-05 00:30:42

标签: php html sql

我正在尝试通过HTML创建一个表单,将用户输入的信息发送到sql数据库。但是,当我们刷新屏幕时,它会发送一个空白版本的数据,如果我们发送带有数据的表单在其中将擦除信息并发送旧表格。

//这是HTML中的表单

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="civilian_whitelist.php" method="post">
    <p>
        <label for="roleplayName">Role Play Name:</label>
        <input type="text" name="roleplayname" id="roleplayName">
    </p>
    <p>
        <label for="playerID">Player ID:</label>
        <input type="text" name="playerid" id="playerID">
    </p>
    <input type="submit" value="Submit">
</form>
</body>
</html>

//这是用于将代码发送到sql数据库的PHP

 <?php

    if (iaView::REQUEST_HTML == $iaView->getRequestType())
    {
        $iaView->display('civilian_whitelist');
    }

    /* Attempt MySQL server connection. Assuming you are running MySQL
    server with default setting (user 'root' with no password) */
    $link = mysqli_connect("HIDDEN", "ericmcho_pro", "HIDDEN", "ericmcho_pro");

    // Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    // Escape user inputs for security
    $roleplayName = mysqli_real_escape_string($link, $_POST['roleplayname']);
    $playerID = mysqli_real_escape_string($link, $_POST['playerid']);

    // attempt insert query execution
    $sql = "INSERT INTO whitelist (Name, UID) VALUES ('$roleplayName', '$playerID')";
    if(mysqli_query($link, $sql)){
        echo "Records added successfully.";
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }

    // close connection
    mysqli_close($link);
    ?>

1 个答案:

答案 0 :(得分:3)

至少应该在运行其余代码之前检查字段是否已设置。

if(isset($_POST['roleplayname'], $_POST['playerid'])){
  //code here
}

if(isset($_POST['submit'])){
  //code here
}

此外,你应该使用关于准备好的声明:

http://php.net/manual/en/mysqli.prepare.php