这是我的第一个关于PHP的项目,并且第一次遇到这个在一天之后无法解决的错误。这里有任何专家和善良的灵魂可以建议如何解决这个错误吗?我的PHP版本是5.6。
非常感谢,
提交表单后,会显示以下错误
致命错误:在第28行调用null上的成员函数prepare()
我的数据库连接编码是
<?php
$DSN= 'mysql:host = localhost; dbname=cms4.2.1';
$ConnectingDB = new PDO($DSN, 'root', '');
?>
Category page that shows line 28 got error on the POD function "prepare"
if(empty($Category))
{
$SESSION["ErrorMessage"] = "All fields must be filled out";
Redirect_to("Categories.php");
} elseif (strlen($Category)<3) {
$SESSION["ErrorMessage"] = "Category Title should be greater than 3
characters";
Redirect_to("Categories.php");
} elseif (strlen($Category)>49) {
$_SESSION["ErrorMessage"] = "Category Title should be less than 50
characters";
Redirect_to("Categories.php");
} else {
global $ConnectingDB;
$sql = "INSERT INTO category(title,author,datetime)";
$sql .="VALUES(:categoryName,:adminName,:dateTime)";
$stmt = $ConnectingDB->prepare($sql); // - > means PDO object rotation -
Line 28
$stmt->bindValue(':categoryName',$Category);
$stmt->bindValue(':adminName',$Admin);
$stmt->bindValue(':dateTime',$DateTime);
$Execute=$stmt->execute();
请协助。非常感谢。
你可能需要在这里删除空格:mysql:host = localhost; dbname=cms4.2.1
将是mysql:host=localhost;dbname=cms4.2.1
另外,将连接语句包装在try-catch块中以查看是否正确连接。
try {
$DSN = 'mysql:host=localhost;dbname=cms4.2.1';
$ConnectingDB = new PDO($DSN, 'root', '');
$ConnectingDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to Database<br/>';
}
catch(PDOException $e){
echo $e->getMessage();
}