MYSQL数据插入查询不起作用

MYSQL data insert query is not working

本文关键字:不起作用 查询 插入 数据 MYSQL      更新时间:2023-09-26

我想将表单中的一些数据插入数据库表"sumation"中。但它不起作用。我使用PhpStorm IDE,它显示没有配置任何数据源来运行这个sql,也没有配置sql方言。问题出在哪里?

<?php
    $db= new PDO('mysql:host=localhost;dbname=test;cahrset=utf8','root','');
    if(isset($_POST['submit'])){
        $id=$_POST['id'];
        $first=$_POST['first'];
        $second=$_POST['second'];
        $third=$_POST['third'];
        $sql="INSERT INTO sumation VALUES($id,'$first','$second','$third')";
        $db->query($sql);
        echo("<script>alert('Data Inserted Sucessfully !')</script>");
    }
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
        ID: <input type="text" name="id"><br>
        First: <input type="text" name="first"><br>
        Second: <input type="text" name="second"><br>
        Third: <input type="text" name="third"><br>
        <button type="submit" class="btn-primary" name="submit">Insert </button>
    </form>
</body>
</html>

您的查询错误,INSERT的语法为

INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)

所以你的查询看起来像

INSERT INTO sumation (id, first, second, third) VALUES ($id, '$first', '$second', '$third')

您也只是假设您的查询已执行。PDO查询在成功时返回一个对象,在失败时返回布尔false,这意味着您可以将其包装成if-语句。

您还应该阅读"如何防止PHP中的SQL注入?"?,这基本上意味着您应该使用准备好的语句。

请尝试

$sql="INSERT INTO sumation VALUES($id,'$first','$second','$third')";

只需更换

$sql="INSERT INTO sumation (id,first,second,third) VALUES ($id,'$first','$second','$third')";

这应该有效:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id=$_POST['id'];
    $first=$_POST['first'];
    $second=$_POST['second'];
    $third=$_POST['third'];
    $conn = new mysqli('localhost', 'root', '', 'test');
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql="INSERT INTO sumation (id,first,second,third) VALUES ($id,'$first','$second','$third')";
    if ($conn->query($sql) === TRUE) {
        echo("<script>alert('Data Inserted Sucessfully !')</script>");
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<form method="post">
    ID: <input type="text" name="id"><br>
    First: <input type="text" name="first"><br>
    Second: <input type="text" name="second"><br>
    Third: <input type="text" name="third"><br>
    <button type="submit" class="btn-primary" name="submit">Insert </button>
</form>
</body>
</html>

正确回答您关于如何保护应用程序免受SQL注入攻击的问题。

SQL注入攻击是指用户在其输入字符串中插入SQL命令,从而允许用户在数据库上运行SQL查询。这意味着他们可以删除整个数据库或打印出所有行。

您可以使用PDO报价功能。

$id=$db->quote($_POST['id']);
$first=$db->quote($_POST['first']);
$second=$db->quote($_POST['second']);
$third=$db->quote($_POST['third']);

或者,我建议您使用PDO准备和执行功能,请阅读此处的文档:http://php.net/manual/en/pdo.prepare.php