首页 > 解决方案 > 致命错误:在第 28 行调用一个成员函数 prepare() on null

问题描述

这是我在 PHP 上的第一个项目,也是第一次遇到这个经过一天的努力确实无法解决的 bug。任何专家和善良的灵魂都可以建议如何解决这个错误吗?我的 PHP 版本是 5.6。

太感谢了,

提交表单后,它显示以下错误

致命错误:在第 28 行调用一个成员函数 prepare() on null

我的数据库连接编码是

<?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();

请协助。太感谢了。

标签: phpmysqlpdo

解决方案


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

推荐阅读