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/

相关文章:

php - 如何选择 id 仅高于空白的行

php - 没有cron的计划PHP脚本执行

c# - MySQL SELECT 命令被拒绝给用户 - MySql.Data.EntityFrameworkCore

mysql - 字段列表中的未知列 - 子查询未找到父变量

php - JS/PHP 'listener' 触发事件

php - 如何在 Amazon SES 服务上通过 php mail 发送邮件?

javascript - 是否可以在没有 Javascript 的情况下将比其父元素更宽且绝对定位的元素居中?

javascript - 弹出框在关闭后第一次点击时不显示

jquery - 使一个 div 滚动到另一个 div 的前面?

php - 警告 : Invalid argument supplied for foreach() in Magento error log