2013-01-18 98 views
1

我正在從mysql_轉換到mysqli。做一些教程。儘管閱讀和搜索該主題,但沒有取得多大成功。我嘗試了一個準備好的語句,但它一直輸出0個結果(即now_rows = 0)。當我手動查詢mySQL表時,會返回一些結果。mySQLi沒有正確選擇數據

mysqli的5.0.96啓用

<? 
include("conn.php"); 
// SELECT sql query 
$sql = "SELECT id, rotation, assignedRad FROM sched_main WHERE thedate = ?"; 
// perform the query and store the result 
$query = $conn->prepare($sql); 
$thedate='2013-01-02'; 
$query->bind_param('s', $thedate); 
$query->execute(); 
// if the $query contains at least one row 
if ($query->num_rows > 0) { 
    // output data of each row from $query 
    while($row = $query->fetch_assoc()) { 
    echo '<br /> id: '. $row['id']. ' - name: '. $row['rotation']. ' - pass: '.  $row['assignedRad']; 
    } 
    $query->free(); 
} 
else { 
    echo '0 results'; 
} 
?> 

問題2:有沒有一種簡單的方法來調試mysqli的?使用mysql_query我只需要echo $ sql;查看SELECT語句在我的調試過程中的作用。 在此先感謝

更新:

這裏是更新的代碼片段的建議如下:

$query->bind_param('s', $thedate); 
if (!$query->execute()) { 
    die($conn->error); 
} 
$query->store_result(); 
// if the $query contains at least one row 
if ($query->num_rows > 0) { 
    // output data of each row from $query 
    while($row = $query->fetch()) { 
    echo '<br /> id: '. $row['id']. ' - name: '. $row['rotation']. ' - pass: '. $row['assignedRad']; 
    } 
    $query->mysqli_free(); 
} 
else { 
    echo '0 results'; 
} 

現在,它與數組$行的值,因爲沒有值輸出:

id: - name: - pass: 
id: - name: - pass: 
id: - name: - pass: 

..等...

我也得到 致命錯誤:調用未定義的方法mysqli_stmt :: mysqli_free()

,當我嘗試免費()我得到: 致命錯誤:調用未定義的方法mysqli_stmt :: free()的

回答

0

我不是確定調試部分,但在調用$query->num_rows之前,可能需要存儲DB執行調用的結果。另外,您可能想要檢查準備和執行是否成功。

... 
if (!$query = $conn->prepare($sql)) { 
    die($conn->error); 
} 
$thedate='2013-01-02'; 
$query->bind_param('s', $thedate); 
if (!$query->execute()) { 
    die($conn->error); 
} 
$query->store_result(); 
if ($query->num_rows > 0) { 
    ... 
} 

詳情參見PHP的文檔上num_rowserror