[英]MYSQL data insert query is not working
我想将某些数据从表单插入数据库表“求和”。 但这不起作用。 我使用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
-statement中。
您还应该阅读有关如何防止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/zh/pdo.prepare.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.