PDO 连接和 bootstrap 日期选择器

PDO connection and bootstrap datepicker

我正在使用 Bootstrap 日期选择器,它应该在我更改日期时从我的数据库中获取有关日期的信息。

现在我正在 jquery 中使用我的 jQuery 脚本调用数据库查询的 PHP 函数。不过,我的问题是,我应该在函数中还是在日期选择器所在站点的顶部包含我的 PDO 连接字符串?

我刚开始想,如果我将它包含在函数中,我想它会在每次日期更改时创建一个新的 PDO 连接对象。我知道一个对象会持续到对象被销毁,但是在整个页面中保持打开状态是否没有问题?

but are there no issues leaving it open through the entire page

是的,在整个请求过程中保持连接打开没有问题。但是每次调用函数时关闭并重新创建新连接是一个问题,因此请避免这种情况。

只创建一次连接,在该页面的整个代码中使用它。

请注意,由于您使用的日期选择器几乎总是前端 JavaScript 代码,因此每次更改时它都会向您的 php 页面发出新的 AJAX 请求一个日期,因此每次都是 new 请求,并且每个新请求的数据库连接都将是 opened/closed。

如果您的连接位于页面顶部的日期选择器处于打开状态,则无法像使用 javascript 那样与新请求共享它。

在这种情况下,连接必须在服务器页面上,数据库根据该请求调用

再补充一点,以帮助解决有关关闭连接的问题。

关闭连接

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

持久连接

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.

Reference