php、mysql、打开数据库花费太长时间

标签 php mysql

我网站上的页面加载时间太长 - 大约 2 秒。在整个代码中使用 microtime 后,我找出了哪里花费了太长时间,并请求帮助以了解如何加快速度。

我用来查找时间的代码是

echo "<BR>3 - ".(microtime(true)-$startTime);  #How long it takes for this page to do
$sqldb=open_database();  #Open the database
echo "<BR>4 - ".(microtime(true)-$startTime);  #How long it takes for this page to do

我的结果是

3 - 5.1140758991241
4 - 6.1172299385071

因此我推断打开数据库的函数需要 1 秒。 用于打开数据库的函数是

//This function is to open the database
function open_database() {
    //Now we will connect to the database
    $sqldb=mysql_connect($_SESSION['hostname'], $_SESSION['dbusername'], $_SESSION['password']) OR die ('Unable to connect to database! Please try again later.');
    mysql_select_db($_SESSION['dbname'], $sqldb);  #Select which database we wish to use - in this case the customer one

    if(empty($sqldb)) {  //If there is no database then we have an error - MASSIVE ERROR!
        header('Location:'.$_SESSION['web_site'].'/error.php');
        die();
    }
    return($sqldb);
}

请注意,SESSION 变量在 mysql_connect 中使用,因此当我更新到生产服务器时,我只需更改一个变量。预生产服务器上的主机名是“locaLhost”。

所以我的问题是 - 为什么打开数据库需要这么长时间?请注意,因为我处于预生产阶段,所以数据库非常小。

最佳答案

session 存储在文件系统中,从文件系统读取也需要时间。如果它们存储在 php 代码中,那么它们将立即可供脚本使用。这可能是您问题的一部分。

让我提供一个可能的解决方案。创建 2 个新文件。

dbconfig.prod.php dbconfig.dev.php

将数据库配置信息放入每个文件中以获得正确的环境。在开发服务器上将 dbconfig.dev.php 符号链接(symbolic link)到 dbconfig.php 在生产服务器上将 dbconfig.prod.php 符号链接(symbolic link)到 dbconfig.php 然后在版本控制中忽略 dbconfig.php

现在你不必做一些非标准的事情,比如数据库配置存储的 session ,它可能会解决你的计时问题。尽管在我看来,1 秒并不是很多额外的时间。

关于php、mysql、打开数据库花费太长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9146960/

相关文章:

php - 使用单个 php 表单将数据添加到两个表

php - 我的 Sql 案例与 PHP if-else 性能对比

php - 使用 mysql 从 php 插入时出现问题

mysql - codeigniter 中的事件记录会自动在每个 where 子句逗号分隔值周围添加引号

MySQL:当特定类型的记录不在另一个表中时如何连接

mysql - 错误 13 (HY000) : Can't get stat of '/tmp/file1.csv' (Errcode: 2) while trying to import CSV file into MariaDB

mysql - 在 Controller laravel 中查询 sql

php - 登录脚本PHP Mysql中的错误

c# - 如何在 Javascript 中读取页面历史记录?

mysql - Phpmyadmin 无法访问数据库