为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
开心每一天1111 2022-09-12 10:12:45
我正在尝试测试一个非常简单的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')";    }?>
查看完整描述

1 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

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


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


<?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注入的影响。


查看完整回答
反对 回复 2022-09-12
  • 1 回答
  • 0 关注
  • 162 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号