MYSQLI:从Ajax调用HTML

时间:2017-03-11 21:40:36

标签: php jquery ajax mysqli

我试图获取数据库查询的结果,该查询几乎总是包含多行数据,从HTML文件中的Ajax调用返回到HTML文件,以便我可以显示它。

index.html

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <title>My Webpage</title>
    <script type="text/javascript">
        //Function for getting data from database
        function getData() {
            $.ajax({
                url: "get_data.php",
                type: "GET",
                success: function(data) {
                    alert("Finished!");
                }
            });
        }
    </script>
</head>
</body>
    <!--I'd like to put a table of data here-->
</body>
</html>

get_data.php

<?php
    include "action.php";

    $sql_query = "SELECT * FROM " . TABLE;

    //Connecting to database
    $mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD, DATABASE);

    //Check database connection
    if($mysqli === false) {
        die ("\nCould not connect:  " . mysqli_connect_error());
    } else {
        echo nl2br("\nConnected successfully! Host info: " .   mysqli_get_host_info($mysqli));
    }

    echo executeQuery($sql_query, $mysqli);
?>

action.php

 <?php
    define("SERVER_NAME", "localhost");
    define("USERNAME", "root");
    define("PASSWORD", "");
    define("TABLE", "data_set");

    $mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD);

    //Check database connection
    if($mysqli === false) {
        die ("\nCould not connect:  " . mysqli_connect_error());
    } else {
        echo nl2br("\nConnected successfully! Host info: " . mysqli_get_host_info($mysqli));
    }

    //Function to execute database queries
    function executeQuery($sql_query, $mysqli) {
        if(mysqli_query($mysqli, $sql_query)){
            echo nl2br("\n\nQuery executed successfully: $sql_query");
        } else {
            echo nl2br("\n\nERROR: Could not able to execute $sql_query. " . mysqli_error($mysqli));
        }
    }
?>

我似乎无法弄清楚如何将查询结果从action.php传递到'get_data.php , back to the original Ajax call from index.html so that I can build my table. I've tried just using echo`,结果是查询,但这不起作用,因为将对象转换为字符串时出错。

2 个答案:

答案 0 :(得分:1)

我没有看到executeQuery函数的任何返回值。 mysqli_query 函数返回 mysqli_result 对象,如果有任何失败,则返回布尔 false 。您可以使用此 mysqli_result 对象来获取所需的数据并将其放入数组中。该数组应编码为json响应,这是Javascript理解的格式。

例如:

function executeQuery($sql_query, $mysqli) {
    $rows = [];
    $result = mysqli_query($mysqli, $sql_query);

    if ($result === false) {
        // Do something if anything goes wrong here like throwing an exception
    }

    while ($row = mysqli_fetch_assoc($result)) {
        $rows[] = $row;
    }

    return $rows;
}

然后你可以调用这个函数来获取数据并将其转换为json,如下所示:

$rows = executeQuery($sql_query, $mysqli);
echo json_encode($rows);

这是最基本的基本方法,但不推荐这种确切的实现方式。输出表的实际列名是一个漏洞,因为每个人都可以看到它们,我会在使用 json_encode 之前遍历它们并进行更改。

答案 1 :(得分:-1)

您定义了 TABLE ,但您的 DATABASE 名称在哪里?你不能只在每个地方写下echo。您必须使用mysqli_fetch_array函数将结果作为数组获取,然后将其作为json发送。我只是在一个脚本中修改了整个代码,猜测,它会有所帮助。

<?php
define("SERVER_NAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "");
define("DATABASE", "YOURDATABASE");
define("TABLE", "YOURTABLENAME");

$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD);

//Check database connection
if ($mysqli === false) {
    die ("\nCould not connect:  " . mysqli_connect_error());
}

//Function to execute database queries
function executeQuery($sql_query, $mysqli)
{
    $result = mysqli_query($mysqli, $sql_query);
    if ($result) {
        //You have to run mysqli_fetch_array to get real data as array
        return mysqli_fetch_array($result);
    }
}

$sql_query = "SELECT * FROM " . TABLE;

//Connecting to database
$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD, DATABASE);

//Check database connection
if ($mysqli === false) {
    die ("\nCould not connect:  " . mysqli_connect_error());
} else {
    //echo nl2br("\nConnected successfully! Host info: " . mysqli_get_host_info($mysqli));
}


//after getting the result send output to brower with json encode and then from your ajax response
// You can handle json data easily.
// And for json response you can't just write echo from everywhere in script. Send either die on failure or result on success
$result = executeQuery($sql_query, $mysqli);

header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);
exit();