2015-08-24 90 views
-1

如何在sql響應爲空的情況下向此代碼添加句柄?如何處理空的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

sql_query是什麼東西的包裝? – Drew

回答

0

你可以這樣做:

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

'is_empty'不是一個通用的PHP函數。 –

+0

@CharlotteDunois謝謝你。在這裏還早;)更新。 – BlackHatSamurai

+0

感謝它現在的作品! :) –

0

fetch_assoc()回報false如果在結果沒有剩餘的行。如果您只提取1行,並且沒有匹配的行,則會在第一次調用時返回false。所以只是測試$id2是truthy還是假:

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'"; 
+0

謝謝,我想通了! :) –