I figured some new comers to PHP might like a simple tutorial on how to connect to a MySQL database.
So let's get started.
I, obviously, use PHP to run this website. All the information on this website, and on many, many, many others is dynamically shown or displayed by PHP.
Here's the code I use for this page itself to connect to my database.
// Connect to the database server
$con = mysql_connect("localhost", "YOUR USERNAME GOES HERE", "YOUR PASSWORD GOES HERE");
if(!$con) {
die("Could not connect to database: ".mysql_error());
}
// Open to the database
mysql_select_db("YOUR DATABASE GOES HERE") or die(mysql_error());
In the second line of code, "$con = mysql_connect("localhost", "YOUR USERNAME GOES HERE", "YOUR PASSWORD GOES HERE");", we are setting a variable called "con". The "$" symbol assigns a variable. The variable holds the code to connect to the database. If you wanted to, you could change the entire code I wrote above to:
// Connect to the database server
mysql_connect("localhost", "YOUR USERNAME GOES HERE", "YOUR PASSWORD GOES HERE");
// Open to the database
mysql_select_db("YOUR DATABASE GOES HERE") or die(mysql_error());
The reason why I don't do that, is because if something goes wrong, I don't get an error message. The next part of the code : if(!$con) {
die("Could not connect to database: ".mysql_error());
} Runs the code (inside the variable "con"), and checks if the condition inside the "if" statement is true. In this case, there is an exclamation mark ("!"), which means not true. So if the connection is not true (well, really, if it doesn't work), the code will display an error message and tell you what's wrong.
The last piece of code:
// Open to the database
mysql_select_db("YOUR DATABASE GOES HERE") or die(mysql_error());
Opens a connection to your database, and if it doesn't work, it displays an error message.
Here, you may notice that instead of using an "if" statement, like before, to display an error message, I simply used "or die(...)". You could really do either way. I did this in the example to show that there is more than one way of doing things. If I wanted to, I could have changed to code to connect to the database itself to:
// Open to the database
$database = mysql_select_db("YOUR DATABASE GOES HERE");
if(!$database) {
die(mysql_error())
}
NOTE: when "//" is in front of a line of code, it makes what ever is on that line a "comment", meaning it is not executed. It is generally used to leave a little note to the person who is writing/changing the code.