php - 使用 mysql 和 session 变量进行多个 Ajax 调用

标签 php jquery mysql ajax session

我为我的公司编写了一个门户,其中有数十个 ajax 调用。对于每个 ajax 调用,目标脚本都会使用 mysql 和 session 变量。在我所做的每一个脚本中:

页面.php

    $.ajax({
            type:"POST",
            data:someData,
            url:target.php,
            success:function(result){
                    someAction
            }
    });

目标.php

   <?php
      session_start(); 
      //target from ajax.php
      require_once('/var/www/lib/db.php');
       ......
       ......
        $_SESSION['someVar'] = $someMysqlResult;

db.php

  $db = new PDO('mysql:host=localhost;dbname=someDB', 'someUser', 'somePassword');

所以我设置了新的 mysql 连接数十次。有没有更好的办法?是否有一个 mysql 资源可以承载所有这些 ajax 调用?

我也启动了数十次 session 。有没有更好的方法在目标脚本上再次打开 session ?

最佳答案

根据documentation ,您可以使用持久连接:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

您应该意识到这样做有一些需要注意的负面缺点:What are the disadvantages of using persistent connection in PDO

关于php - 使用 mysql 和 session 变量进行多个 Ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40917691/

相关文章:

javascript - 我想在提交表单时显示确认弹出窗口

javascript - 可折叠订单状态表跨度问题

javascript - 如何根据屏幕尺寸更改 Angular JS 中的弹出框位置?

php - 如何使用 PHP 和 MYSQL 自动显示多个图表?

php json_encode 返回空值

php - 如何正确下载 .vcf 文件

mysql - 指标/报告生成问题

python - 通过 sqlalchemy 执行时启用执行多个语句

javascript - 来自全日历事件点击的 Bootstrap 模式调用

php - 匹配注册商标符号的正则表达式