我有一个PHP表单,它应该向SQLite数据库中的图书表添加一本书。表单提交了,但是一本书没有添加到我的数据库中。
<?php
session_start();
require("books.php");
require("layout.php");
$db=sqlite_open ("products.db", 0666, $error);
echo $header;
echo "<p>
<a href='./index.php'>Bookshop</a></p>";
echo "<h1> Add Books </h1>
<p>
<form action='' method='get' id='AddBook'>
Author: <input type='text' name='Author'><br>
Title: <input type='text' name='Title'><br>
Brief_Synopsis: <input type='text' name='Synopsis'><br>
ISBN_Number: <input type='text' name='ISBN'><br>
Publisher: <input type='text' name='Publisher'><br>
imgNumber (save img with this name under /img/): <input type='text' name='imgNum'><br>
Price: <input type='text' name='Price'><br>
Category 1: <input type='text' name='Cat1'><br>
Category 2: <input type='text' name='Cat2'><br>
<input type='submit' value='Submit' name='Submit'>
</form>
</p>";
if(isset($_POST['Submit'])){
$author = $_POST['Author'];
$title = $_POST['Title'];
$Synopsis = $_POST['Synopsis'];
$ISBN = $_POST['ISBN'];
$Publisher = $_POST['Publisher'];
$imgNum = $_POST['imgNum'];
$Price = $_POST['Price'];
$Cat1 = $_POST['Cat1'];
$Cat2 = $_POST['Cat2'];
sqlite_query($db,"INSERT INTO Books (Author, Title, Brief_Synopsis, ISBN_Number, Publisher, imgNumber, price, cat1, cat2) VALUES ('$_POST[Author]', '$_POST[Title]', '$_POST[Synopsis]', '$_POST[ISBN]', '$_POST[Publisher]', '$_POST[imgNum]', '$_POST[Price]', '$_POST[Cat1]', '$_POST[Cat2]')");
echo("Book Added!");
$dbh = null;
}
?>
为什么这段代码没有正确更新我的数据库?在我添加if语句之前,它每次加载页面时都会向数据库中添加一本空书,但现在它提交并重置表单,我的URL看起来是正确的,但数据库中没有添加项目。
您的代码正在无声地失败,因为您在表单中使用的是GET方法,而您使用的是POST数组。
- 将表单的方法更改为POST
我还需要指出,您当前的代码对SQL注入是开放的。使用准备好的语句,或将PDO与准备好的声明一起使用、它们更安全。
<input type="hidden" name="checkSubmit" value="Submitted">
if(isset($_POST['checksubmit']))
我还注意到,sql注入着眼于$_POST['myvariable']
,这使得之前对变量的检查充其量是多余的。