【问题标题】:PHP form doesn't insert into SQL databasePHP 表单不插入 SQL 数据库
【发布时间】:2020-05-22 00:18:36
【问题描述】:

我正在尝试测试一个非常简单的 PHP 表单,它将输入插入 SQL 数据库。连接工作正常,但是当我刷新它时数据没有出现在数据库中。我只有两个文件,一个 index.html 和一个 process.php。

index.html:

<html>
<head>Testing</head>
<body>
    <div id="frm">
        <form action="process.php" method=POST>
            <p>
                <label>Username</label>
                <input  type="text" id="stuff" name="stuff">
            </p>
            <p>
                <input type="submit" id="btn" value="Login">
            </p>
        </form>
    </div>
</body>
</html>

进程.php:

<?php
    $userinput = $_POST['stuff'];
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "testing";

    $conn = new mysqli($servername, $username, $password, $database);

    if ($conn->connect_error)
    {
        die("connection failed: " . $conn->connect_error);
    }

    else
    {
        echo "Connected successfully "; 
        echo $userinput;
        $sql = "INSERT INTO `entries`(`input`) VALUES ('$userinput')";
    }
?>

【问题讨论】:

  • 如果提交查询,脚本的哪一部分?没有

标签: php html mysql sql mysqli


【解决方案1】:

您的代码没有向数据库提交查询,它正在打开连接但没有提交查询,如果您在 PHP 中使用 mysqli,请参见下面的提交查询请求


... else {
  # this submits the query
  $conn -> query ($sql);
}

【讨论】:

  • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
【解决方案2】:

问题是您实际上并没有运行查询。您刚刚将查询字符串分配给了一个变量,因此它不会在 MySQL 中执行。

您的代码容易受到SQL injection 的攻击,因此我提出了一个解决方案:

<?php
$userinput = $_POST['stuff'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "testing";

$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error)
{
    die("connection failed: " . $conn->connect_error);
}
else
{
    echo "Connected successfully "; 
    echo $userinput;
    $sql = "INSERT INTO `entries` (`input`) VALUES (?)";
    if ($stmt = $conn->prepare($sql)) { // Prepare statement
        $stmt->bind_param("s", $userinput); //Bind the string (s), with the content from $userinput to the statement marker (?)
        $stmt->execute(); // Run (execute) the query
        $stmt->close(); //clean up
}

此代码应该可以工作,并且还可以保护您免受 SQL 注入。

【讨论】:

【解决方案3】:

您需要使用 mysqli 的函数 mysqli_query,它将参数作为连接对象,如 $conn,第二个参数将是要执行的 sql 查询。 像这样

$sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");

为了防止sql注入,你必须使用PDO,因为PDO使用paramBind来保护注入。

【讨论】:

    【解决方案4】:

    尚未对其进行全面测试,但我已修复您的查询。

    $sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");
    

    还将帖子部分更改为:&lt;form action="process.php" method="POST"&gt;

    这应该可以为您解决问题

    还要确保使用函数:mysqli_real_escape_string 来逃避恶意用户输入以防止 SQL 注入。

    另一件事:您可以将 localhost 更改为 127.0.0.1。我认为这更可靠,尽管在大多数情况下都是一样的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多