从数据库检索到PHP中的表

时间:2014-11-25 15:41:06

标签: php database

我试图从数据库中检索数据并将其显示在php中的表中

我试过这个

 <?php



 // array for JSON response
 $response = array();


 // include db connect class
 require_once __DIR__ . '/db_connect.php';

 // connecting to db
 $db = new DB_CONNECT();
 mysql_query("SET NAMES 'utf8'");
 // get all products from products table
 $result = mysql_query("SELECT *FROM glossary") or die(mysql_error());

 // check for empty result
 if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["glossaries"] = array();
     echo "<table>";
 echo "<tr>";
 echo "<th>Symbol</th>";
 echo "<th>Name</th>";
 echo "<th>Description</th>";
 echo "<th>Chapter</th>";
 echo "</tr>";
while ($row = mysql_fetch_array($result)) {

  echo "<tr>";
echo "<td>". $row['Symbol'] ."</td>";   
echo "<td>". $row['Name'] ."</td>"; 
echo "<td>". $row['Description'] ."</td>";
echo "<td>". $row['ID_Chapter'] ."</td>";
 echo "</tr>";


}
     echo "</table>";
header("Content-type: application/json; charset=utf-8");
// success
$response["success"] = 1;

// echoing JSON response
 } else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";

 }
 ?>

但是我会在浏览器中得到一个非常奇怪的结果,它会打印表标签td,tr ...以及它们之间的值,如下所示:

 <table><tr><th>Symbol</th><th>Name</th><th>Description</th><th>Chapter</th></tr><tr><td>θ </td><td></td><td></td><td>8</td></tr><tr><td>A ⊂ B</td><td>Proper subset / strict subset</td><td>Subset has fewer elements than the set</td><td>1</td></tr><tr><td>A'</td><td>Complement </td><td>Event A does not occur</td><td>1</td></tr></table>

为什么?

1 个答案:

答案 0 :(得分:3)

header("Content-type: application/json; charset=utf-8");

那......不是JSON数据。那个HTML。例如:

echo "<table>";

默认Content-type可能是HTML,因此您可以完全删除header行。如果你想要明确,你可以:

header("Content-type: text/html; charset=utf-8");

基本上发生的事情是,您明确告诉浏览器呈现HTML,而只是将其视为JSON数据。这就是为什么它没有呈现HTML。