What's quicker; including another file or querying a MySQL database in PHP?

后端 未结 12 1703
闹比i
闹比i 2021-01-12 04:29

In PHP, which is quicker; using include(\'somefile.php\') or querying a MySQL database with a simple SELECT query to get the same information?

12条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 05:13

    Including a file should almost always be quicker. If your database is on another machine (e.g. in shared hosting) or in a multi-server setup the lookup will have to make an extra hop.

    However, in practice the difference is probably not going to matter. If the list is dynamic then storing it in MySQL will make your life easier. Static lists (e.g. countries or states) can be stored in a PHP include. If the list is quite short (a few hundred entries) and often used, you could load it straight into JavaScript and do away with AJAX.

    If you are going the MySQL route and are worried about speed then use caching.

    $query = $_GET['query'];
    $key = 'query' . $query;
    if (!$results = apc_fetch($key))
    { 
        $statement = $db->prepare("SELECT name FROM list WHERE name LIKE :query");
        $statement->bindValue(':query', "$query%");
        $statement->execute();
        $results = $statement->fetchAll();
        apc_store($key, $results);
    }
    
    echo json_encode($results);
    

提交回复
热议问题