2015-05-04 85 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