2012-12-10 114 views
-5

中給出的布爾值這是我一直用來嘗試連接到數據庫並從中檢索數據的代碼,但它沒有正確顯示圖像。所有其他內容均正確顯示。mysql_fetch_array()期望參數1是資源,在

//This php quote is test2.php 
<?php 

$dbhost='localhost'; 
$dbuser='root'; 
$dbpass=''; 
$db='dynamic'; 

$con = mysql_connect("localhost","elemental",""); 
if (!$con) 
    { 
    die('Could not connect: ' . mysql_error()); 
    } 



mysql_selectdb($db); 

?> 


<?php 
include 'test2.php'; 

$query="selelct * from data"; 
$result=mysql_query($query); 

while ($data=mysql_fetch_array($result)) { 

echo '<h3>' . $data['id'] . '</h3>'; 
    echo '<h3>' . $data['name'] . '</h3>'; 

} 


?> 
+0

您無法檢查'mysql_query'的結果。它在出現錯誤時返回'false',而不是返回'mysql_fetch_array'所期望的語句句柄。這也是相關工具欄中這些問題中最後一個問題的重複。 **單挑!** PHP的未來版本是*棄用和刪除mysql_'系列函數。如果你仍然在學習PHP,現在將是[切換到PDO](http://php.net/book.pdo)或[mysqli](http://php.net/book.mysqli)的好時機。 。 – Charles

+0

其'mysql_select_db'而不是'mysql_selectdb' –

+0

'select * from data''' select'from data' –

回答

3

你有2個錯別字:

$query="selelct * from data"; 

應該是:

$query="select * from data"; //select not selelct 

mysql_selectdb($db); 

應該是:

mysql_select_db($db); 
+1

FWIW,'mysql_selectdb'的奇怪實例是一個PHP4主義。額外的下劃線是稍後添加的,並添加了別名。看到這是一個肯定的消息,用戶一直在閱讀過時的教程,或從未改進原有的PHP知識。 – Charles

0

您的代碼中存在一些疏漏或問題。包括不知道的原因重複自己,並且在你進步的時候沒有測試你的變量/動作。

<?php 

$dbhost = 'localhost'; 
$dbuser = 'root'; 
$dbpass = ''; 
$dbbase = 'dynamic'; 

// WAS 
// $con = mysql_connect("localhost","elemental",""); 
// why have your variables above if you hardcode them? 
if(!($con = mysql_connect($dbhost , $dbuser , $dbpass))){ 
    error_log('MySQL Server Connection Failed - '.mysql_error()); 
    // Never echo your errors publicly 
    die('Cannot connect to database, but I am not going to show you why publicly.'); 
} 
if(!mysql_select_db($dbbase)){ 
    error_log('MySQL Database Connection Failed - '.mysql_error()); 
    // Never echo your errors publicly 
    die('Cannot connect to database, but I am not going to show you why publicly.'); 
} 

include('test2.php'); 

// WAS 
// $query="selelct * from data"; 
// check your spelling! 
$query = 'SELECT * FROM data'; 

if(!($result = mysql_query($query))){ 
    error_log('MySQL Query Failed - '.mysql_error()); 
    die('Cannot query the database, but I am not going to show you why publicly.'); 
} 
if(!mysql_num_rows($result)){ 
    echo 'No Records Found'; 
}else{ 
    while($d = mysql_fetch_array($result)){ 
    echo '<h3>'.$d['id'].'</h3><h3>'.$d['name'].'</h3>'; 
    } 
} 
相關問題