PHP Mysql获取的数据为空


PHP Mysql fetched data blank

我的php代码有点问题。。

$stmt = $db->prepare("SELECT * FROM mytable WHERE TheGroup = :SearchName ORDER BY TheTime DESC");
$stmt->bindParam(':SearchName', $request, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = count($result);
for ($i = 0; $i < $count; $i++) {
    $mTheAvatar = $result[$i]->TheAvatar;
    $mTheDirection= $result[$i]->TheDirection;
    $mTheGroup = $result[$i]->TheGroup;
    $mTheMedia = $result[$i]->TheMedia;
    $mTheMessage = $result[$i]->TheMessage;
    $mTheSenderName= $result[$i]->TheSenderName;
    $mTheThumbImage = $result[$i]->TheThumbImage;
    $mTheTime = $result[$i]->TheTime;
    $mTheMediaExtension = $result[$i]->TheMediaExtension;
    echo "hello";
    echo $mTheAvatar;
    echo "    <- this is avatar";
}

如果我执行Var_dump(),我会看到请求的数据没有问题。如果我回显变量,它们是空白的。。我已经检查了三遍表列名是否正确。。

$mTheAvater是表中的一张图片,如果这能提供线索的话,但其余的都是空白的,所以不确定发生了什么?!?

您可以测试:

$mTheAvatar = $result[$i]['TheAvatar'];

正如我所知,在FETCH_ASSOC中,它以上述结构返回数据。

您试图将它们当作对象来读取,但PDOStatement::fetchAll返回一个数组,因此您的代码应该如下所示:

for ($i = 0; $i < $count; $i++) {
    $mTheAvatar = $result[$i]['TheAvatar'];
    $mTheDirection= $result[$i]['TheDirection'];
    .
    .
    .
    .
    echo "hello";
    echo $mTheAvatar;
    echo "    <- this is avatar";
}

如果您想处理对象,您应该使用PDOStatement::fetchObject

这应该更好——1)它使用foreach;2) unset();3) 不同结构

 $stmt = $db->prepare("SELECT * FROM mytable WHERE TheGroup = :SearchName ORDER BY TheTime DESC");
$stmt->bindParam(':SearchName', $request, PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($results){
  foreach($results as $result_data) {
    echo $result_data['TheAvatar'];
    echo $result_data['TheDirection'];
     //and so on
    unset($result_data);
  }
}
else{
    echo 'Empty';
}