【问题标题】:how do I return an sql result with ajax in JSON format [duplicate]如何以 JSON 格式返回带有 ajax 的 sql 结果 [重复]
【发布时间】:2012-01-24 15:32:34
【问题描述】:

可能重复:
JSON encode MySQL results

这是使用Mysql fetch 数组来显示结果。如何使用 JSON 编码替换以下标签。 我正在尝试从数据库中获取一个表,这完成了输出数据的工作......这是使用 Mysql 获取数组来显示结果。如何使用 JSON 编码替换以下标签。

PHP File 
<?php
$q=$_GET["q"];

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

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

【问题讨论】:

标签: php ajax json


【解决方案1】:
<?php
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
print json_encode($rows);

【讨论】:

  • 非常感谢@kenaniah
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-07
  • 2021-12-20
  • 2018-05-14
  • 2023-02-03
  • 2016-03-10
  • 2017-04-02
  • 2018-08-18
相关资源
最近更新 更多