I’ve got the following saved into my dbConnect.php file
$host = 'localhost';
$username = 'root';
$pass = 'mypass';
try {
$dbh = new PDO("mysql:host=$host;dbname=horh_new", $username, $pass);
} catch (PDOException $e) {
echo $e->getMessage();
}
What is the best method to include this into my script? Right now, I’ve got a function to insert a user into the database which does something like this:
function insertUser($username) {
include("dbConnect.php"); // i'd like to not have to include this each time
$query = $dbh->prepare("INSERT INTO users (username) values (?)");
$query->bindParam(1, $username);
$query->execute();
}
Obviously, the more functions I have the more times I have to include this dbConnect.php file. Should I instead include it into a class with private variables for $username, $host, and $pass (so there are no conflicts when using the same variables passed into the function?
Then include the class once in the header of my script instead of in every single function? I’m quite new to PDO, so I’d like to figure out the most efficient method of doing this. Thanks.
Every time you include that, you are opening a new connection in the scope of that function. Simply include it on your front-facing web file and global your db connection for each function. Do not include this file more than once, otherwise you will be opening that many more connections, which causes unnecessary slowdowns.
index.php example:
somefunctions.php: