Hey everyone! In this post we’re going to talk about how to use PHP to connect to a database.
The first thing we’re going to do is create a configuration file. I named it “config.php”.
It’s important to create a config.php file so that if you only have to change on file if you ever have to update your password, username, or host.
Always be sure to use detailed variable names so that you know with out a doubt what they are. Being as specific as possible is a really good habit to get into.
We’re going to set up our variables to look like
<?php $database_name = ''; $database_username = ''; $database_password = ''; $database_host = ''; ?>
Simply fill in the appropriate values into the variables and save the file.
Now we need to go to the file that we want to actually connect to the database with. In my example, I used “connect.php”
The first thing you want to do, is to include the configuration file we created moments ago, “config.php”
To do this, you simply use the php function “include()” like so
<? include('config.php'); ?>
Now that we have the configuration file included, we can go ahead and start requesting a connection to the database.
We’ll start off using the “mysql_connect()” function, supply it with the host, username, and password variables from “config.php”, and place a error message incase anything goes sticky.
<? include('config.php'); mysql_connect($database_host,$database_username,'$database_password') OR die('could not connect to database!'); ?>
Okay so if you were to save the file, and view it right now you wouldn’t see anything, unless there was an error connecting to the database. So if you’re stuck here, make sure your database information is all correct. If you need help creating a database, check out my video on How To Make A MySQL Database.
Once we’ve made the connection to the database server (which is “localhost”), it’s time to tell the server what database we want to really connect to. For this we use the “mysql_select_db()” function and simply supply the “$database_name” variable. Ofcourse, we’re going to throw in a error message incase anything goes wrong.
<? include('config.php'); mysql_connect($database_host,$database_username,$database_password) OR die('could not connect to database!'); mysql_select_db($database_name) OR die('could not select database'); ?>
If you’re able to access the page with no errors, then you are successfully connected to your database! You can go on to the next step of grabbing information from it, or inserting the data into it.
Thanks a lot for watching! Please let me know if you have any questions! Thanks!