2016-01-05 64 views
-2

我試圖運行mysql刪除事務時遇到致命錯誤,所以我搜索了類似的問題,它變得明顯使用mysqli_fetch_assoc是解決這個問題的方法。試了幾次,但顯然做錯了什麼,感謝任何幫助。我如何使用mysqli_fetch_assoc修復「致命錯誤:不能使用mysqli_result類型的對象作爲數組」

這裏是我的代碼

<?php 
$selected_admin = find_admin_by_id($_GET["admin"]); 
if (!$selected_admin) { 
    redirect_to("sadmin.php"); 
} 

while ($admin = mysqli_fetch_assoc($selected_admin)) { 
    $admin_id = $selected_admin["admin_id"]; 
} 

$sql = "delete from admin where admin_id = {$admin_id} limit 1"; 
$result = mysqli_query($connection, $sql); 

if ($result && mysqli_affected_rows($connection) == 1) { 
    $SESSION["message"] = "Admin successfully deleted."; 
    redirect_to("sadmin.php"); 
} else { 
    $SESSION["message"] = "Admin was not deleted successfully."; 
    redirect_to("sadmin.php?admin={$admin_id}"); 
} 
?> 

,功能正在呼叫的是這個

function find_admin_by_id($admin_id) { 
    global $connection; 

    $query = "select * from admin where admin_id = {$admin_id} LIMIT 1"; 
    $current_admin = mysqli_query($connection, $query); 
    confirm_query($current_admin); 
    return $current_admin; 
} 
+0

在你的while循環中,'$ selected_admin [「admin_id」]'應該是'$ admin [「admin_id」]''。 '$ selected_admin'是結果,你從中得到一個數組並將其保存在'$ admin'中。 '$ admin'現在是一個包含當前行的數組。 –

+0

@JonathanKuhn像魔術一樣工作,謝謝你指出我。 – Mena

回答

0

您正在使用錯誤的變量在while循環和我的其他隊友也提到一小時前,這裏是正確的代碼略有變化:

<?php 
$selected_admin = find_admin_by_id($_GET["admin"]); 
if (!$selected_admin) { redirect_to("sadmin.php"); 
} 
while ($admin = mysqli_fetch_assoc($selected_admin)) 
{ 
$admin_id = $admin["admin_id"]; 
} 

if(intval($admin_id) > 0){ 
$sql = "delete from admin where admin_id = {$admin_id} limit 1"; 

$result = mysqli_query($connection, $sql); 

if ($result && mysqli_affected_rows($connection) == 1) 
{ 
$SESSION["message"] = "Admin successfully deleted."; 

redirect_to("sadmin.php"); 
} 
else { 
$SESSION["message"] = "Admin was not deleted successfully."; redirect_to("sadmin.php?admin={$admin_id}"); 
} 
} 
?> 

我改變了什麼:

將$ selected_admin更改爲$ admin。 並在執行DELETE STATEMENT之前添加條件。

+1

感謝您在刪除前添加if條件的建議。幫助很多。 – Mena

相關問題