在過去的兩個小時里,我一直在嘗試創建一個連接到 SQLite 的簡單插入表單。出于某種原因,插入新記錄不起作用。當我使用php -S localhost:1234. 單擊“提交”按鈕后,我的表單只是清空而沒有任何插入。
我的資料庫名為database.db,表名為students_tb,表中的列是id、sname和score。
這是我的代碼,它基于https://www.youtube.com/watch?v=cyl0Oj3rmmg&list=PLU70qqWW4frENsWYAm-tAKp2ZJQ_dt3WR&index=8。我檢查并重新檢查了 3 分鐘長的教程,但未能成功追蹤我的錯誤。我想這一定是一個愚蠢的錯誤,但我真的找不到。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Student</title>
<style>
label, input {
display: block;
}
</style>
</head>
<body>
<h1>Add student to database</h1>
<?php
// has the form been submitted?
// if not, show the HTML form
if (!isset($_POST['submit'])) {
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label for="sname">Student's Name</label>
<input type="text" name="sname" required>
<label for="score">Score</label>
<input type="number" name="score" required>
<button type="submit">Submit</button>
</form>
<?php
} else {
try {
$db = new PDO("sqlite:database.db");
$sql = "INSERT INTO students_tb (sname, score) VALUES (:sname, :score)";
$stat = $db->prepare($sql);
// named params
$sname = filter_input(INPUT_POST, "sname");
$stat->bindValue(":sname", $sname, PDO::PARAM_STR);
$score = filter_input(INPUT_POST, "score");
$stat->bindValue(":score", $score, PDO::PARAM_INT);
$success = $stat->execute();
// does the value exist?
if ($success) {
echo "The student has been added to the database.";
} else {
echo "The student has NOT been added to the database.";
}
$db = null;
} catch (PDOException $e) {
// for development
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
}
?>
</body>
</html>
uj5u.com熱心網友回復:
自從我使用 PHP 已經有一段時間了,但我認為問題可能出在表單的 HTML 代碼中。你有:
<button type="submit">Submit</button>
并且您的 PHP 代碼正在檢查名為 submit 的變數的值,但該欄位沒有名稱,只有型別。應該是:
<button type="submit" name="submit">Submit</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/350188.html
上一篇:在父目錄中創建資料庫
