PDO没有返回任何行

时间:2015-06-10 15:16:00

标签: php mysql pdo

此设置不会从数据库返回任何内容。这是我第一次使用PDO,所以我可能会遗漏一些东西。它根本没有丢失任何错误,只是一个空洞的结果。

$results = array();

$stmt = $bd->prepare("Select Beer.Beer_Name, Prices.Price, Prices.Shop_Name FROM Beer, Prices WHERE Beer.Beer_Name = Prices.Beer_Name AND Shop_Id = :retailer");

    $stmt->bindValue(':retailer', $retailer);


$stmt->execute();



$results[0] = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($results[0]);

1 个答案:

答案 0 :(得分:0)

您不需要预先设置数组,并且可以在使用$query->RowCount()之前检查结果。以下是使用错误捕获的示例:

try {
    // Enabled throwing errors - you can remove this after debugging
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // Prepare the statement
    $stmt = $bd->prepare("Select Beer.Beer_Name, Prices.Price, Prices.Shop_Name FROM Beer, Prices WHERE Beer.Beer_Name = Prices.Beer_Name AND Shop_Id = :retailer");

    // You can also use bindparams, I like to use execute and pass and array so it is shorter
    $stmt->execute(array(
        ':retailer' => $retailer
    ));
    if($stmt->RowCount()==0) {
        // Do stuff when no results are found (without an error)
    } else {
        $Results = $stmt->FetchAll();
    }

// Catch any exceptions and put the error into $e
} catch (Exception $e) {
    // Echo the error we got - you should only output errors when debugging
    echo $e->GetMessage();
}

如果您有疑问,请告诉我,但此方法应该会给您带来任何数据库错误。如果您没有收到错误,那么您的查询就不会返回任何内容。