PHP使用PDO时读取没有记录的表会报错,如何处理?Call to a member function fetch() on null
<?php//连接代码如下$servername="localhost";$username="root";$password="pwdpdd!";$dbname="co...
<?php
//连接代码如下
$servername = "localhost";
$username = "root";
$password = "pwdpdd!";
$dbname = "color";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
//echo "连接成功";
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET NAMES utf8");
$conn->exec("SET character_set_server=utf8");
}
catch(PDOException $e)
{
//echo $e->getMessage();
}
?>
<?php //以下为读取代码
$stmt = null;
try {
$sql = "SELECT COUNT(*) AS total FROM colours";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $stmt->fetch()) //如果表里没有记录,这句会报错
{……}
}
catch(PDOException $e)
{
//echo $e->getMessage();
}
?> 展开
//连接代码如下
$servername = "localhost";
$username = "root";
$password = "pwdpdd!";
$dbname = "color";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
//echo "连接成功";
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET NAMES utf8");
$conn->exec("SET character_set_server=utf8");
}
catch(PDOException $e)
{
//echo $e->getMessage();
}
?>
<?php //以下为读取代码
$stmt = null;
try {
$sql = "SELECT COUNT(*) AS total FROM colours";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $stmt->fetch()) //如果表里没有记录,这句会报错
{……}
}
catch(PDOException $e)
{
//echo $e->getMessage();
}
?> 展开
展开全部
if(is_object($stmt ))先加一个这个判断,判断返回的变量是不是对象再决定如何调用!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询