php - 致命错误:在第 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();
请协助。太感谢了。
解决方案
您可能需要在此处删除空格: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();
}
推荐阅读
- python - Python 获取 URL,打开输出文件,写入输出,关闭输出文件,结束 for 循环
- .net - Visual Studio 无法识别 Mac 上的项目
- javascript - 使用不同类型的 Javascript 标签在 HTML 文档中实现全局变量
- php - 当我需要传递自定义选项时如何使用 PHP curl_multi_init() 用法?
- android - 如何在颤动中绘制自定义动态高度曲线形状?
- arrays - Swift数组中texview中的所有字符
- javascript - 如果我有多个具有相同选项的选择标签,如何将警报按钮添加到单选选项?
- python - 如何在pygame中将矩形对象限制在给定坐标的边缘?
- python - python转换列的日期时间格式
- reactjs - 元素停止移动后如何将焦点设置为输入?