我该如何处理空的sql响应?

时间:2015-08-24 16:48:29

标签: php mysql sql response

如果sql响应为空,我如何为此代码添加句柄?

<?php
$userReferrals_query = sql_query("SELECT id as id2 FROM balances WHERE email = '$address'");
$id2 = fetch_assoc($userReferrals_query); 


$userReferrals_query2 = sql_query("SELECT COUNT(*) AS referrals FROM balances WHERE referredby = '".$id2['id2']."'");
$referrals = fetch_assoc($userReferrals_query2); 
?>

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

if(empty($id2)){
//Code to handle empty response
}

答案 1 :(得分:0)

如果结果中没有剩余行,

fetch_assoc()将返回false。如果您只是获取1行,并且没有匹配的行,则在第一次调用时返回false。因此,只需测试$id2是真还是假:

if ($id2) {
    // do referrals query
}

或者您可以简单地将两个查询与JOIN

组合在一起
$userReferralsQuery = sql_query("SELECT COUNT(*) AS referrals 
                                 FROM balances AS b1
                                 JOIN balances AS b2 ON b1.referred_by = b2.id
                                 WHERE b2.email = '$address'";