我正在尝试返回从我的数据库中提取的名称的 json 数组。我不确定我在这里缺少什么,但它永远不会收到警报呼叫。返回的数据不一定是 json,我只是先尝试这种方法。它完成了 INSERT 调用,我知道它正在返回正确的数据集。我的代码有什么问题?
Javascript
function showDB() {
$.post('example.php', $('#infoForm').serialize(), function(data) {
var json = $.parseJSON(data);
$.each(json, function(i, item) {
alert(item);
});
}, "json");
}
PHP
<?php
$host = "www.host.com";
$user = "user";
$pwd = "password";
$db = "exampleDB";
$conn = mysqli_connect($host, $user, $pwd)or die("Error connecting to database.");
mysqli_select_db($conn, $db) or die("Couldn't select the database.");
$name = $_POST['name'];
$color = $_POST['color'];
$nameArray = array();
$stmt = mysqli_stmt_init($conn);
$query = "INSERT INTO people VALUES (?, ?)";
mysqli_stmt_prepare($stmt, $query) or die("Failed to prepare statement.");
mysqli_stmt_bind_param($stmt, "ss", $name, $color);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$query = "SELECT name, COUNT(*) AS dupes FROM people GROUP BY name ORDER BY dupes DESC LIMIT 20";
$result = mysqli_query($conn, $query);
while ($row = $mysqli_fetch_array($result)) {
array_push($nameArray, $row['name']);
}
echo json_encode($nameArray);
mysqli_close($conn);
?>