php - 使用 PHP 和 AJAX 检索数据库数据

标签 php jquery mysql ajax

我尝试使用 AJAX 从数据库检索数据,但没有成功。这些是我正在使用的代码。我在控制台中没有看到任何特定错误。

HTML:

<button type="button" name="result_submit" id="result_submit" >Submit</button>
<div class="result" id="result" name="result"> </div>

Jquery:

$(document).ready(function(e) {
    $('#result_submit').click(function() {

        $.ajax({
            url  :"Income.php",
            type :'POST',
            success: function(data){
                $("#result").html(data);
            }
        });
    }); 
});

Income.php内容:

<?php

include_once 'dbConnection.php';

$stmt = mysqli_stmt_init($conn);

$income = "select SUM(amount) as incomeNumber FROM wp_formdata WHERE entry_type='Income'";

    if(!mysqli_stmt_prepare($stmt,$income)) 

        {
            $message =  '<h1 style="color:red;padding-top:5%;">SQL Error !!</h1>';
        } 
        else 
        {
            mysqli_stmt_execute($stmt);
            $result= mysqli_stmt_get_result($stmt);
            $income_sum=mysqli_fetch_assoc($result); 
            $TotIncome= "Total Income is ".$income_sum['incomeNumber'];
        }
?>

dbConnection.php 有连接详细信息:

<?php

$dbServername = "localhost";    
$dbUsername = "root";
$dbPassword = "";
$dbName = "wordpress";

$conn= mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

?>

有人可以指导我如何解决这个问题

最佳答案

您需要从 PHP 文件中回显您的数据:

$income = "select SUM(amount) as incomeNumber FROM wp_formdata WHERE entry_type='Income'";
$response = '';

if (! mysqli_stmt_prepare($stmt,$income)) {
     $response = '<h1 style="color:red;padding-top:5%;">SQL Error !!</h1>';
} else {
     mysqli_stmt_execute($stmt);
     $result = mysqli_stmt_get_result($stmt);
     $income_sum = mysqli_fetch_assoc($result); 
     $response = "Total Income is ".$income_sum['incomeNumber'];
}

echo $response;

关于php - 使用 PHP 和 AJAX 检索数据库数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52928306/

相关文章:

php - 将 MySQL 表列数组插入到新的 MySQL 表中

javascript - 如何动态填充 javascript 函数的选项

javascript - jQuery.each() 带有 ajax 的目标元素,始终以循环中的最后一项为目标

javascript - 如何在php中发送get请求并接收json数据

php - 在 TLS 握手中不支持 SNI 的服务器是否可以毫无问题地启用 SNI

javascript - 在 jQuery 函数之间共享变量

php - UTF-8 换行符出现在 phpMyAdmin 中,但不出现在网页上

mysql - 获取多个表数据而不损失性能?

php - laravel-snappy:文件未创建

php - 请求的链接库 openssl 安装了错误的版本