对于 mySQL,我是个新手,对于 PDO 更是如此。我正在尝试创建一些简单的插入代码,但我不断收到服务器错误。我觉得这与定义$STH
两次有关。这是我的代码:
$dsn = "mysql:host=localhost;dbname=Menu_Items";
$user = "root";
$pass = "root";
// Connect to database
try{
$DBH = new pdo($dsn, $user, $pass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
// Define user input as $food
$name = $_POST['food'];
$STH->bindParam(':name', $name);
// Insert user input into table
$STH = $DBH->prepare("INSERT INTO foods ( name ) VALUES ( :name )");
$result = $DBH -> query($STH);
if($result){
echo("<br>Input data is succeed");
}else{
echo("<br>Input data is fail");
}
此 php 代码连接到一个简单的 html 表单:
<form id="menu_input" name="menu_input" method="post" action="insert.php">
<table>
<thead>Enter a new item</thead>
<tr>
<th><label for="food">Food</label></th>
<td><input type="text" name="food" id="food" placeholder="Food Name" required></td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table>
</form>
我一直在做研究,但在让它发挥作用时遇到了一点困难。想法?