从数据库中读取条目

时间:2015-05-04 06:11:39

标签: php html pdo

是否有人能够在下面的代码中找出问题所在?它只显示一个空白页面。我是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 个答案:

答案 0 :(得分: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>