2015-05-04 81 views
0

是否有人能夠找出以下代碼中出錯的地方?它只是顯示一個空白頁面。我是PDO的新手,總是使用mysqli,但有人告訴我嘗試PDO,因爲我的頁面顯示阿拉伯字符時出現問題。從數據庫中讀取條目

<html> 
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> 
<?php 
/* Connect to an ODBC database using driver invocation */ 
$dsn = 'mysql:dbname=testdb;host=127.0.0.1;charset=UTF8;' 
$user = 'dbuser'; // don't hardcode this...store it elsewhere 
$password = 'dbpass'; // this too... 

try { 
    $dbh = new PDO($dsn, $user, $password); 
} catch (PDOException $e) { 
    echo 'Connection failed: ' . $e->getMessage(); 
} 

$sql = "SELECT :column FROM :table"; 
$opts = array(
    ':column' => 'Name', 
    ':table' => 'Mothakirat' 
); 
$dbh->beginTransaction(); 
$statement = $dbh->prepare($sql); 
if ($statement->execute($opts)) { 
    $resultArray = array();  // If so, then create a results array and a temporary one 
    $tempArray = array();   // to hold the data 

    while ($row = $result->fetch_assoc()) // Loop through each row in the result set  
    { 
    $tempArray = $row; // Add each row into our results array 
    array_push($resultArray, $tempArray); 
    } 
    echo json_encode($resultArray);  // Finally, encode the array to JSON and output the results 
} 
$dbh->commit(); 
</html> 
+1

打開錯誤報告,在頁面頂部:error_reporting(E_ALL);然後發回任何你不確定的錯誤。 – Chris

+0

什麼也沒有顯示@Chris – Sam

+0

你也應該告訴PDO拋出異常,以便它會告訴你在與數據庫有關的情況下出了什麼問題。將此作爲第四個參數添加到您的「新PDO()'調用中:'數組(PDO :: ATTR_ERRMODE => PDO :: ERRMODE_EXCEPTION)' – jeroen

回答

1

這在我的IDE中沒有檢查到分析錯誤。我使用netbeans,它非常好,可以在多個平臺上使用。

<html> 
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> 
<?php 

/* Connect to an ODBC database using driver invocation */ 
$dsn = 'mysql:dbname=testdb;host=127.0.0.1;charset=UTF8;'; 
$user = 'dbuser'; // don't hardcode this...store it elsewhere 
$password = 'dbpass'; // this too... 

try { 
    $dbh = new PDO($dsn, $user, $password); 
} catch (PDOException $e) { 
    echo 'Connection failed: ' . $e->getMessage(); 
} 

$sql = "SELECT :column FROM :table"; 
$opts = array(
    ':column' => 'Name', 
    ':table' => 'Mothakirat' 
); 
$dbh->beginTransaction(); 
$statement = $dbh->prepare($sql); 
if ($statement->execute($opts)) { 
    $resultArray = array();  // If so, then create a results array and a temporary one 
    $tempArray = array();   // to hold the data 

    while ($row = $result->fetch_assoc()) // Loop through each row in the result set  
    { 
    $tempArray = $row; // Add each row into our results array 
    array_push($resultArray, $tempArray); 
    } 
    echo json_encode($resultArray);  // Finally, encode the array to JSON and output the results 
} 
$dbh->commit(); 
?> 
</html> 
+0

我同意。下一個問題:輸出json是無效的;-) – jeroen

+0

json正在mysqli罰款。 @jeroen – Sam

+0

@Sam你也輸出html,所以最終的結果將不是有效的json。如果你當然需要...... – jeroen