【问题标题】:Issue with SQL Insert query using POST and PHP使用 POST 和 PHP 的 SQL 插入查询问题
【发布时间】:2019-06-13 03:52:27
【问题描述】:

基本上,我有以下 PHP 脚本,我试图将其用于将新记录插入到我的数据库中。

当在 PHP 脚本中硬编码值以插入所有内容时,当我使用 POST 方法时,这些值永远不会写入我的数据库。以下是我的脚本:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

$customer = $_POST['customerName'];
$manufacturer = $_POST['manufacturerName'];
$model = $_POST['model'];
$serial = $_POST['serial'];

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}


$sql = "INSERT INTO Equipment (customer, manufacturer, model, serial)
VALUES ('$customer', '$manufacturer', '$model', '$serial');";

if (mysqli_multi_query($conn, $sql)) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

【问题讨论】:

  • 您能检查一下 $_POST 变量中的内容吗?
  • 同时发布html内容。
  • 请出示您的html代码。
  • 找到问题后,或许可以修复你存在的海量SQL注入安全漏洞。
  • 原帖中应该有这种信息.. 将print_r($_POST);添加到页面顶部,让我们知道它返回什么

标签: php json post


【解决方案1】:

我刚刚测试了这一切。您的 PHP 代码按原样工作。要查看来自帖子的变量,您可以添加:

var_dump( $_POST );

在代码的顶部。这会告诉你进来的东西是正确的。我用来完成这项工作的 HTML 如下:

<html>
<body>
    <form action="post.php" method=POST>
        Customer: <input type="text" name="customerName"><br />
        Manufacturer: <input type="text" name="manufacturerName"><br />
        Model: <input type="text" name="model"><br />
        Serial: <input type="text" name="serial"><br />
        <input type="submit">
    </form>

</body>

请注意,输入的名称与您在 PHP 中所期望的名称完全相同。

此外,您应该在收到变量时对变量进行某种清理,否则,您很容易受到各种 SQL 注入的攻击。

一个简单的方法是使用addslashes()。像这样:

$customer = addslashes( $_POST['customerName'] );
$manufacturer = addslashes( $_POST['manufacturerName'] );
$model = addslashes( $_POST['model'] );
$serial = addslashes( $_POST['serial'] );

这并不能完全拯救你,但总比没有好。无论如何,我使用你的确切 PHP 和我在上面发布的 HTML 让它工作。

【讨论】:

  • 使用您的 html 成功创建了记录,但由于某种原因使用邮递员,我不断收到数组 (0)
  • 在邮递员中,我将其设置为 POSTBodyx-www-form-urlencoded
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 2020-05-07
  • 2011-07-29
  • 1970-01-01
相关资源
最近更新 更多