This isn't really a problem per se, but more of a question about efficiency.
Basically, I have an index.php file that handles the main code for the site I'm building. Within that code are several JavaScript/JQuery functions that use $.ajax() to handle data using other php files.
There are two functions I use that interact with a MySQL database (Note these aren't the fully implemented functions).
One for updating the database:
function updateDB(text) {
$.ajax({
url: "update_db.php",
type: "POST",
data: {text:text},
});
}
and one for getting information from the database:
function displayText() {
$.ajax({
url: "display_text.php",
type: "POST",
data: {},
});
}
At the top of both files ("update_db.php" and "display_text.php"), I include a .php file that connects to the database using PDO:
<?php require_once('connect_to_db.php'); ?>
However, this seems inefficient because the database is accessed twice when I run my index.php file, once for updating the database and once for displaying the contents of the database.
My question is this: is there any drawback to connecting to the database twice? My assumption is that this would bog down database operations and execute functions slower.
If there are drawbacks, is there a way to only connect to the database once even though the main index.php calls two different files that each have to connect to the database?
I'm mainly interested in learning how to write more efficient code, as well as get opinions on how to make things like file-handling more efficient. Any suggestions are welcome!