首先是我的代码:
database.php (已建立连接,因此我可以使用require)
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$port = 8889;
$database = "oopdb";
try{
$conn = new PDO("mysql:host=$servername; dbname=$database; port=$port", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET NAMES 'utf8'");
}catch(Exception $e){
echo "Error: " . $e->getMessage();
exit;
}
?>
然后我的主PHP文件格式为:
<!DOCTYPE html>
<html>
<head>
<title>Forms with PDO</title>
</head>
<body>
<?php
require("database.php");
if(isset($_POST['submit'])){
//trying to insert data into the database
try{
// prepare and bind
$stmt = $conn->prepare("INSERT INTO clients (phonenumber, firstname, lastname, address, note) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssss', $phonenumber, $firstname, $lastname, $address, $note);
// set parameters and execute
$phonenumber = $_POST['number'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$note = $_POST['note'];
$stmt->execute();
}catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
}
?>
<h2>The Form</h2>
<hr />
<br />
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
Number: <input type="text" name="number" value="" />
<br /><br />
First Name: <input type="text" name="firstname" value="" />
<br /><br />
Last Name: <input type="text" name="lastname" value="" />
<br /><br />
Address: <input type="text" name="address" value="" />
<br /><br />
Notes: <input type="text" name="notes" value="" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<br />
<hr />
</body>
</html>
所以现在由于某种原因,当我点击提交时,我无法将表单中的数据插入到我的数据库中。我一直收到这个错误:
致命错误:在第19行的/Users/lucasantos/Sites/oop_testing/stack.php中调用未定义的方法PDOStatement :: bind_param()
我已经看到了使用bind_param和将数据插入数据库的多种方法。这个方法具体来自W3schools HERE
我已多次查看整个代码,多次尝试但仍无法正常工作。我甚至查看了bind_param文档,我相信我正确使用它。有人请帮忙。
其他一些信息:
- 如果重要的话,我会通过MAMP在本地主机上这样做。
- 我还有一行 id ,但我没有包含它,因为它设置为自动增量。
谢谢!