如果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);
?>
答案 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'";