2013-04-05 24 views
-1

用什麼來取代mysql_result用mysqli替換mysql_result

即時看一個教程,但它是在2011年,所以它現在不工作。 這裏的情況是,如果你告訴我怎麼在這裏代替mysql_result,並把什麼括號我會很感激

function update_count() { 
    global $link; 
    $query = "SELECT `count`, FROM `hits_count`"; 
    if($query_run = mysqli_query($link, $query)) { 
     $count = mysql_result($query_run, 0, 'count'); 
     $count_inc = $count + 1; 
     echo $count; 
    } 
} 
update_count(); 
+0

你能解釋一下你的問題嗎? – 2013-04-05 16:29:08

+0

你不能在mysql對象上使用mysql_result,看看Rocket Hazmats的答案。 (它應該是mysqli_result) – bestprogrammerintheworld 2013-04-05 16:40:03

+2

我完全看到了什麼被問到。我沒有看到什麼大不了的。 – KickingLettuce 2013-09-06 21:17:17

回答

0
function update_count() { 
    global $link; 
    $query = "SELECT `count` FROM `hits_count` ;"; 
    if(($result = mysqli_query($link, $query)) && $result->num_rows >= 1) { 
     $count = 0 ; 
     while($row = $result->fetch_assoc()){ 
      $count+= $row['count'] ; 
     } 
     echo $count; 
    } 
} 

通常會更好該鏈接進入該功能:

function update_count($link) { 
    $query = "SELECT `count` FROM `hits_count` ;"; 
    if(($result = mysqli_query($link, $query)) && $result->num_rows >= 1) { 
     $count = 0 ; 
     while($row = $result->fetch_assoc()){ 
      $count+= $row['count'] ; 
     } 
     echo $count; 
    } 
} 
+1

'global $ link'是不好的做法,並佔用額外的資源。你應該把它傳遞給函數。 – Kermit 2013-04-05 16:33:28

+0

請加入失敗檢查... – Ihsan 2013-04-05 16:34:51

+0

已更新。 – vikingmaster 2013-04-05 16:35:01

6

mysqli_query給你一個mysqli_result object。從那裏,你可以得到你想要的價值。

if($query_run = mysqli_query($link, $query)) { 
    // This gets you one row at a time, use a while if there are multiple rows 
    // while($row = mysqli_fetch_assoc($query_run)){} 
    $row = mysqli_fetch_assoc($query_run); 
    $count = $row['count']; 
    // Do whatever with $count 
} 
3

爲了支持tadman的回答言簡意賅與證明代碼

與mysqli的,PDO有一個長期追求mysql_result相當於:

function update_count() { 
    global $link; 
    $query = "SELECT `count` FROM `hits_count`"; 
    $stmt = $link->prepare($query); 
    $stmp->execute(); 
    return $stmt->fetchColumn(); 
} 
echo update_count(); 

任何人誰說的mysqli不超過PDO差,必須嘗試首先使用預處理語句將數組綁定到IN()語句中。

+0

PDO比'mysqli'更清潔,更容易審覈。我可以考慮使用'mysqli'的唯一原因是,如果你的系統是由沒有安裝PDO的暴君運行的。 – tadman 2013-04-05 17:21:26