我正在爲我的英語老師開發一個小型項目,這是我第一次對數據庫做任何事情。我有一個名爲Books
的表格,有四列:Id, Title, Link, and Rating
。這個想法是,用戶可以提交他們最近閱讀的書的標題,在goodreads上的鏈接,以及5星評分。 (我還沒有任何輸入驗證,但是在完成當前問題後我會補充說明)。PHP爲SQL添加唯一ID
問題發生在Id列中。我試圖用PHP和SQL來獲取整個表中最大的Id,然後將新添加的書(行)的Id設置爲比最大的一個更大。
這裏是我的HTML:
<form action="bookSubmit.php" method="post">
Book Title: <input type="text" name="title"><br>
Goodreads Link: <input type="text" name="link"><br>
Rating (1 to 5): <input type="number" name="rating" min="1" max="5"><br>
<input type="submit" value="submit">
</form>
和bookSubmit.php:
<?php
$servername = "localhost";
$username = "[My username]";
$password = "[My password]";
$dbname = "PullJosh_books";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$newId = $conn->query("SELECT MAX(Id) FROM Books"); // Replacing this line with $newId = and then manually typing in the current highest Id works (meaning everything else is all set).
$newId++;
$sql = "INSERT INTO Books (Id, Title, Link, Rating)
VALUES ('". $newId ."', '" . $_POST['title'] . "', '" . $_POST['link'] . "', '" . $_POST['rating'] . "')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
當我在phpMyAdmin的SQL選項卡運行SELECT MAX(Id) FROM Books
,我得到2,這是正確的。
如果您碰巧注意到任何安全問題(除了未驗證輸入),請讓我知道這一點。
爲什麼不只是自動增加它呢? – Ghost 2014-12-07 13:11:19