致命错误:在第28行的null上调用成员函数prepare()

时间:2019-03-05 08:33:27

标签: php mysql pdo

这是我的第一个PHP项目,并且第一次遇到这个bug,经过一天的努力,它确实无法解决。  请问任何专家和友善的人在此建议如何解决此错误?我的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();

请协助。非常感谢。

1 个答案:

答案 0 :(得分:2)

您可能需要在此处删除空格: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();
}