PHP 表单不会插入到 SQL 数据库中

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


索引.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')";

    }

?>


开心每一天1111
浏览 163回答 1
1回答

明月笑刀无情

问题是您实际上并没有运行查询。您刚刚将查询字符串分配给变量,因此它不会在MySQL中执行。您的代码容易受到SQL注入的攻击,因此我提出了一个解决方案:<?php$userinput = $_POST['stuff'];$servername = "localhost";$username = "root";$password = "";$database = "testing";$conn = new mysqli($servername, $username, $password, $database);if ($conn->connect_error){&nbsp; &nbsp; die("connection failed: " . $conn->connect_error);}else{&nbsp; &nbsp; echo "Connected successfully ";&nbsp;&nbsp; &nbsp; echo $userinput;&nbsp; &nbsp; $sql = "INSERT INTO `entries` (`input`) VALUES (?)";&nbsp; &nbsp; if ($stmt = $conn->prepare($sql)) { // Prepare statement&nbsp; &nbsp; &nbsp; &nbsp; $stmt->bind_param("s", $userinput); //Bind the string (s), with the content from $userinput to the statement marker (?)&nbsp; &nbsp; &nbsp; &nbsp; $stmt->execute(); // Run (execute) the query&nbsp; &nbsp; &nbsp; &nbsp; $stmt->close(); //clean up}此代码应该有效,并且还可以保护您免受SQL注入的影响。
打开App,查看更多内容
随时随地看视频慕课网APP