2011-11-25 51 views
2

我寫下面的代碼從表中讀取行:無法獲取的mysqli bind_param綁定變量

$query = "SELECT ........FROM ............WHERE........AND ID = ?"; 
$conn = new Connection(); 
$stmt = $conn->mysqli->prepare($query); 
$stmt->bind_param('i', $_SESSION['id']); 
$stmt->execute(); 
echo 'Num rows = '.$stmt->num_rows(); 

下面是連接的代碼();

define('SERVER', 'localhost'); 
define('USER', 'root'); 
define('PASS', 'xxx'); 
define('DB', 'xxx'); 

class Connection{ 
     var $mysqli = null; 

     function __construct(){ 
      try{ 
       if(!$this->mysqli){ 
        $this->mysqli = new MySQLi(SERVER, USER, PASS, DB); 
        if(!$this->mysqli) 
         throw new Exception('Could not create connection using MySQLi', 'NO_CONNECTION'); 
       } 
      } 
      catch(Exception $ex){ 
       echo "ERROR: ".$e->getMessage(); 
      } 
     } 
    } 

如果我呼應查詢和Navicat的與ID等於$ _SESSION [「身份證」]的值運行它,它不會返回我的行。但在網頁上,它顯示輸出爲:

Num rows = 0 

代碼有什麼問題?請注意,echo $ _SESSION ['id']顯示值。

感謝

回答

1

存儲你的結果設定store_result(),然後訪問$stmt->num_rows的屬性,而不是方法。 (請勿使用()

$query = "SELECT ........FROM ............WHERE........AND ID = ?"; 
$conn = new Connection(); 
$stmt = $conn->mysqli->prepare($query); 
$stmt->bind_param('i', $_SESSION['id']); 
$stmt->execute(); 

// Call store_result() before accessing num_rows() 
$stmt->store_result(); 

// And access num_rows as a property, not a method 
echo 'Num rows = '.$stmt->num_rows; 
+0

非常感謝。這工作。 –