使用php,ajax从数据库中获取数据

Posted

技术标签:

【中文标题】使用php,ajax从数据库中获取数据【英文标题】:Get data from database using php,ajax 【发布时间】:2019-11-26 16:57:23 【问题描述】:

我有一个简单的部分,我在其中显示来自数据库的数据,我的数据库看起来像这样。

现在我有四个按钮,看起来像这样

当用户单击上述按钮之一时,它会显示此

所以现在当用户选择 construction 并接下来选择 Egypt' in the console and clicks buttonconfirmdisplays [855,599075], user can select multiple countries, this works as expected forconstruction ,power,oil`,

现在我想如果用户例如单击这四个按钮中的All available industries 按钮,然后选择例如Egypt 并单击confirm 它应该显示 埃及建筑、石油、电力部门总项目的总和855+337+406 =1598 和两个部门的总预算总和1136173

这是我的解决方案

html

<div id="interactive-layers">
    <div buttonid="43" class="video-btns">
        <span class="label">Construction</span></div>
    <div buttonid="44" class="video-btns">
        <span class="label">Power</span></div>
    <div buttonid="45" class="video-btns">
        <span class="label">Oil</span></div>
    <div buttonid="103" class="video-btns">
        <span class="label">All available industries</span>
    </div>
</div>

这里是js ajax

$("#interactive-layers").on("click", ".video-btns", function()
    if( $(e.target).find("span.label").html()=="Confirm" ) 

        var selectedCountries = [];

        $('.video-btns .selected').each(function () 
            selectedCountries.push( $(this).parent().find("span.label").html() ) ;
        );

        if( selectedCountries.length>0 ) 
            if(selectedCountries.indexOf("All available countries")>-1) 
                selectedCountries = [];
            


         else 

            return;
        

        var ajaxurl = "";
        if(selectedCountries.length>0) 
            ajaxurl = "data.php";
         else 
            ajaxurl = "dataall.php";

        

        $.ajax(
            url: ajaxurl,
            type: 'POST',
            data: 
                    countries: selectedCountries.join(","),
                    sector: selectedSector
            ,
            success: function(result)
                console.log(result);
                result = JSON.parse(result);
                $(".video-btns").each(function () 
                    var getBtn = $(this).attr('buttonid');
                    if (getBtn == 106) 
                        var totalProjects = $("<span class='totalprojects'>"+ result[0] + "</span>");
                        $(this).append(totalProjects)
                    else if(getBtn ==107)
                        var resultBudget = result[1]
                        var totalBudgets = $("<span class='totalbudget'>"+ '&#36m' +" " + resultBudget +"</span>");
                        $(this).append( totalBudgets)
                    
                );
                return;
              
        );
    
);

这里是获取所有dataall.php的php

$selectedSectorByUser = $_POST['sector'];
 $conn = mysqli_connect("localhost", "root", "", "love");
 $result = mysqli_query($conn, "SELECT * FROM meed");
 $data = array();

 $wynik = [];
$totalProjects = 0;
$totalBudget = 0;

 while ($row = mysqli_fetch_array($result))
 
    if($row['Sector']==$selectedSectorByUser ) 
     $totalProjects+= $row['SumofNoOfProjects'];
     $totalBudget+= $row['SumofTotalBudgetValue'];
    
 
 echo json_encode([ $totalProjects, $totalBudget ] );
exit();
?>

这里是data.php

<?php

$selectedSectorByUser = $_POST['sector'];
$countries = explode(",", $_POST['countries']);

//var_dump($countries);
 $conn = mysqli_connect("localhost", "root", "", "meedadb");
 $result = mysqli_query($conn, "SELECT * FROM meed");
 $data = array();

 $wynik = [];
$totalProjects = 0;
$totalBudget = 0;

 while ($row = mysqli_fetch_array($result))
 
    if($row['Sector']==$selectedSectorByUser && in_array($row['Countries'],$countries ) ) 
    // array_push($data, $row);
     $totalProjects+= $row['SumofNoOfProjects'];
     $totalBudget+= $row['SumofTotalBudgetValue'];
    
 

 // array_push($wynik, $row);
 echo json_encode([ $totalProjects, $totalBudget ] );
//echo json_encode($data);
exit();
?>

现在当用户点击All available industries btn 并选择一个国家时,我会在控制台上看到[0,0]

我需要改变什么才能得到我想要的?任何帮助或建议将不胜感激,

【问题讨论】:

phpMyAdmin 是数据库前端,而不是数据库。您不会从中获取数据。 注意:object-oriented interface to mysqli 明显不那么冗长,使代码更易于阅读和审核,并且不容易与过时的mysql_query 接口混淆,因为缺少单个i 会导致麻烦。示例:$db = new mysqli(…)$db-&gt;prepare("…") 过程接口很大程度上是 PHP 4 时代引入 mysqli API 时的产物,不应在新代码中使用。 如果要从多个表中获取数据,请执行多个查询或使用 JOIN。请注意,在与国家打交道时,通常最好使用数字标识符或标准化代码以避免歧义或拼写错误。 ISO-3166 指定每个国家/地区的代码。 更新您的问题并添加预期结果..(使用文本..不是图像) 用 bount 100 更新了问题检查 【参考方案1】:

您可以使用 SQL JOIN 运算符,或者在这种情况下,隐式连接将是最干净的:

$result = mysqli_query($conn, "SELECT * FROM construction, power, oil_and_gas, industrial WHERE construction.Countries = power.Countries AND power.Countries = oil_and_gas.Countries AND oil_and_gas.Countries = industrial.Countries");

您需要 WHERE 条件,以便它知道每个不同表的行是如何相互关联的。您可以使用表格的别名将其缩短一点:

$result = mysqli_query($conn, "SELECT * FROM construction as C, power as P, oil_and_gas as G, industrial as I WHERE C.Countries = P.Countries AND P.Countries = G.Countries AND G.Countries = I.Countries");

但是,在这种情况下,我认为您可能需要考虑更改数据库的结构。似乎您在它们之间重复了很多列。也许这些都可以在一个表中,带有一个“类型”列,指定它是否是电源、构造等。然后你可以只查询一个表并按国家名称分组以获得所有结果,而无需跨 4 的混乱连接表格。

【讨论】:

嗨,谢谢,我会去看看,IceMetalPunk 我希望我能把它做成一张桌子,但我不知道我有什么你认为有可能单表? 绝对有可能。就像我建议的那样,它们都具有相同的三列:国家、项目总数和总预算价值 ($m) 的总和。因此,如果您只是创建一个包含这三列的表,加上一个“类型”列,您可以将所有数据放入该表中,“类型”根据需要指定功率、构造等。 (旁注:列名中确实不应该有空格或括号等特殊字符;如果您不小心,以后可能会导致代码问题。也许将它们更改为 Country、Project_Total 和 Budget_Sum_M?) 我尝试了不同的组合,但是 :( 如果你不介意你可以在 excel 中显示我吗???真的我试过了,我想不通 不推荐在 SQL 中使用隐式连接。您应该使用JOIN ON 子句 @Dharman 只要包含足够的 WHERE 子句以确保连接符合预期,是否有理由不使用隐式连接?【参考方案2】:

单个表看起来不错。

(此答案的其余部分不完整,但可能有用。)

首先,让我们设计请求数据的 URL。

.../foo.php?industry=...&country=...

但是,与其在客户端中对“全部”进行特殊封装,不如在服务器中进行。即行业的最后一个按钮会生成

    ?industry=all

并且 PHP 代码不会在 WHERE 子句中包含这个:

    AND industry IN (...)

&amp;country=all&amp;country=egypt,iran,iraq 类似

现在,让我简要介绍一下 PHP:

$wheres = array();

$industry = @$_GET['industry'];
if (! isset($industry))  ...issue error message or use some default... 
elseif ($industry != 'all') 
    $inds = array();
    foreach (explode(',', $industry) as $ind) 
        // .. should test validity here; left to user ...
        $inds[] = "'$ind'";
    
    $wheres[] = "industry IN (" . implode(',', $inds) . )";


// ... repeat for country ...

$where_clause = '';
if (! empty($wheres)) 
    $where_clause = "WHERE " . implode(' AND ', $wheres);

// (Note that this is a generic way to build arbitrary WHEREs from the data)

// Build the SQL:

$sql = "SELECT ... FROM ... 
           $where_clause
           ORDER BY ...";
// then execute it via mysqli or pdo (NOT mysql_query)

现在,让我们谈谈使用 AJAX。或不。有 2 个选择:

您可以通过GET 调用PHP 并让PHP 显示一个新页面。这意味着 PHP 将构建结果表。 您可以使用 AJAX 来请求数据。这意味着 javascript 将构建结果数据。

选择哪种可能取决于您更熟悉哪种语言。

【讨论】:

您好,感谢您的回答,但有点困惑我有两个 php 文件 data.phpdataall.php 我是否需要添加另一个 php 文件,例如 allindsturies.php,?不擅长 php,请你把你的答案说清楚,这就是为什么我加了 100 的原因,因为我需要一个明确的答案, @user9964622 - 只有 1 个用于处理行业(全部或部分)和国家(全部和部分)的 php 文件。注意“全部”的测试。 .php 中的 code 解释 url 以决定生成什么 SQL。我写了大约一半的代码。 您不应该使用 @ 来消除 PHP 错误。错误和警告是你的朋友。 @Dharman - one 使用@ 是一种简单明了的方式,可以说“这个参数是可选的我会检查它. 这既不容易也不需要。像在 if 中一样使用空合并运算符或 isset【参考方案3】:

在你的dataAll.php中

如果你有选择All available industries 你不应该检查部门,因为你需要所有部门(最终你应该检查国家) 所以你应该避免检查这种情况

<?php

$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = [];

$wynik = [];
$totalProjects = 0;
$totalBudget = 0;

while ($row = mysqli_fetch_array($result)) 
    $totalProjects += $row['SumofNoOfProjects'];
    $totalBudget += $row['SumofTotalBudgetValue'];

echo json_encode([$totalProjects, $totalBudget]);

【讨论】:

您好,当我单击按钮时仍然存在疤痕所有可用行业并单击阿尔及利亚并单击确认我得到 [0,0] :( 我现在要放弃了,但是当我选择另一个行业时,例如建筑或power or oil 我得到了我想要的结果 :( 除了所有可用的行业 btn :( 那么 ajax 呢?也许我需要添加All available industries 的条件?因为如果用户最后点击按钮All available countries,我用来获取数据的dataall.php 然后dataall.php 被调用,它返回的正是我想要的,

以上是关于使用php,ajax从数据库中获取数据的主要内容,如果未能解决你的问题,请参考以下文章

使用 php 和 jquery ajax 从 mysql 数据库中获取数据

如何在提交到 PHP 之前使用 AJAX 从选择标签中获取数据?

使用 php/ajax 选择下拉菜单后从数据库中获取客户信息

从php文件+ajax获取数据

使用 jQuery 的 $.ajax( ) 函数从 php 文件中获取 JSON 数据不起作用

如何使用 bootstrap 和 Ajax 根据所选 ID 从 MySQL 数据库中获取数据?