PHP MySQL使用$\u POST变量插入查询不起作用
我试图将变量插入数据库中的一个表中,由于某种原因,insert查询没有将我的值插入到所述数据库中。我已经测试了“test_input”函数,它工作得很好,我知道连接正在工作,因为我稍后在代码中使用的一个SELECT查询正在工作。我也知道输入是在$_PostSuperGlobal中,所以我认为这可能与insert查询有关,排除了其他可能性。这个查询有什么问题吗?以下是我的php代码:PHP MySQL使用$\u POST变量插入查询不起作用,php,mysqli,insert,Php,Mysqli,Insert,我试图将变量插入数据库中的一个表中,由于某种原因,insert查询没有将我的值插入到所述数据库中。我已经测试了“test_input”函数,它工作得很好,我知道连接正在工作,因为我稍后在代码中使用的一个SELECT查询正在工作。我也知道输入是在$_PostSuperGlobal中,所以我认为这可能与insert查询有关,排除了其他可能性。这个查询有什么问题吗?以下是我的php代码: function test_input($data) { $dat
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = test_input($_POST['name']);
$date = test_input($_POST['date']);
$datestring = date('Y-m-d',strtotime(test_input($_POST['date'])));
$venue = test_input($_POST['venue']);
$town = test_input($_POST['town']);
$connection = new mysqli("Example","Example","Example","Example");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($_POST != []) {
$connection->query("INSERT INTO events (Name, Date, Venue, Town) VALUES(" . $name . ", " . $datestring . ", " . $venue . ", " . $town . ")");
}
这是我的HTML表单代码,如果有什么问题
<div class="tr" id="addevent">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="td">
<input type="text" name="name">
</div>
<div class="td">
<input type="text" name="date">
</div>
<div class="td">
<input type="text" name="venue">
</div>
<div class="td">
<input type="text" name="town">
</div>
<div class="td">
<input type="submit" value="Add Event">
</div>
</form>
</div>
它不起作用,因为您正在创建的动态SQL insert语句将在值列表中包含不带引号的字符串,因此格式不正确。话虽如此,您真的不应该这样做,因为它容易受到一种非常常见的攻击,称为。您可能想检查您的状况$\u POST!=[]
。也许你可以改为测试isset($\u POST['name'])
。或任何其他必须存在的表单参数。在if语句中尝试echo,看看是否执行了它。请将$\u SERVER['PHP\u SELF']
作为您的操作删除。我知道你有htmlspecialchars()
,但其中任何一个都像是黑客的天堂。请参阅此处了解更多信息,并了解为什么htmlspecialchars本身就是一个问题-