2016-12-03 149 views
0

我有三個文件conn.php,在conn.php我有我的數據庫連接func.phpindex.phpindex.phpfunc.php我已經計數數的函數我已經包括了連接文件列注意:未定義的變量:NUM

func.php

<?php 
function countusers($connection, $column, $table) 
{ 
    $stmt = mysqli_prepare($connection, " 
            SELECT 
             COUNT($column) 
            FROM 
             $table"); 
    if($stmt) 
    { 
     mysqli_stmt_bind_result($stmt, $num); 
     mysqli_execute($stmt); 
     mysqli_stmt_fetch($stmt); 
     mysqli_stmt_close($stmt); 
    } 
    return $num; 
} 

但它似乎沒有工作,我嘗試添加的功能連接文件和它的工作。

這裏是我的索引文件

的index.php

<?php 
require_once "conn.php"; 
include "func.php"; 
echo countusers($conn, "id", "mods"); 

conn.php

<?php 
$conn = mysqli_connect("localhost", "root", "", "test", 3306); 
if(!$conn) 
{ 
    echo "An Error Occurred"; 
} 
+0

你有什麼錯誤嗎? – Raptor

+1

也許你最好告訴我們'conn.php',因爲它看起來應該對我有用,除非連接出現問題 – RiggsFolly

+1

不用注意'注意:未定義變量:num' –

回答

1

在php.net中快速閱讀,說bind_result必須在執行後發生......我沒有運行這個,所以只有它的建議。

所以,你可以嘗試...

//... SNIP... 
    if($stmt) 
    { 
     mysqli_stmt_execute($stmt); // Changed this to mysqli_stmt_execute  
     mysqli_stmt_bind_result($stmt, $num); 
     mysqli_stmt_fetch($stmt); 
     mysqli_stmt_close($stmt); 
    } 
    else { 
     $num = 0; 
    } 
    return $num; 
// ... SNIP ... 

還有什麼是在$語句是假的情況下$ NUM的默認值?你需要決定和設置。

更新:在任何原因導致stmt失敗的情況下,添加了$ num的默認值。自從我運行這段代碼後,它就可以工作了。

代碼片段DOES中提出的更改爲$ num提供了一個值,而原始代碼沒有。

至於所使用的實際方法/實現的有效性是另一回事,這個答案直接解決了手頭的問題。

+0

已經修復了這個問題,謝謝 –

+0

Grand,但是請注意可以添加由@RiggsFolly和其他人提供的錯誤報告代碼建議,因爲這是每個人在調試時都需要的重要工具這些東西。 – TimBrownlaw

+0

這個答案是錯誤的,它不能被刪除,因爲它被接受。我希望我有能力消除這種垃圾,儘管什麼愚蠢的OP認爲 –

0

試試這個

error_reporting(E_ALL); 
 
require_once "conn.php"; 
 
require_once "func.php"; 
 

 
echo countusers($conn, "id", "mods");

+0

如果涉及'mysqli_',這是一個更好的錯誤報告集'ini_set('display_errors',1);函數ini_set( 'log_errors',1);使用error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);' – RiggsFolly