我为我的公司编写了一个门户,其中有数十个 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/