None of our previous PHP tutorials have dealt with a database yet, and that is for the sole reason that not everyone has access to a database, however for those who do this tutorial will teach you the basics on how you can connect to your database. We wont be covering SQL queries and the conversion of SQL queries into PHP in this tutorial, you can look for a tutorial on that later on. Before we begin it’s important to note that this tutorial is geared towards those of you who are utilizing PHP 5.4 or earlier. As of PHP 5.5 the mysql_* functions are deprecated and I highly recommend you utilize the methods within our PHP Data Objects tutorial. First I suggest we get the hang of this.
Lets start by defining some variables. We will need to define the$dbuser, $dbpass, $dbhost
and $db
variables (at least those are the names I always use – you can obviously set the names of these variables to anything you want). These will hold the username and password for access to the database, the database host (99% of the time its localhost) and the database name. Here is how we accomplish this:
$dbuser = "mysql_username"; $dbpass = "mysql_password"; $dbhost = "localhost"; $db = "db_name";
Now we just fill in the username, password, host (if needed), and database name with our own information.
Now we can use those variables to connect to the MySQL server. To do this we need to follow the mysql_connect
format of host, username, password.
mysql_connect($dbhost, $dbuser, $dbpass);
Now we need to select the database we wish to work with. We do this with the mysql_select_db
function. Now if you know any SQL queries now is a perfect time to run them. When you are finished you can close the connect with the mysql_close();
function. Here is the complete code:
$dbuser = "mysql_username"; $dbpass = "mysql_password"; $dbhost = "localhost"; $db = "db_name"; mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($db); // Query etc goes here mysql_close();
Wow very nice tutorial about database connection. Thanks for the posting this blog. Can you post the tutorial for Image uploading and delete. I have some problem in deleting the image.
You mean a tutorial on how to upload and delete images and store the image info into a database? I’ll put one up this coming week. —
Michael Boguslavskiy
[email protected]
[email protected]
Well it took a little bit longer than I had expected to put together – it’s been rather hectic around here. Alas here it finally is:
http://rapidpurple.com/blog/tutorials/php-tutorials/file-upload-via-phpmysql/
Hi, I see people use MYSQL database .. is that standard? is there any other option which I must evaluate before joining the mySQL band-wagon?
@Metalp3n, good one .. cool … Do you have a complete tutorial for PHP somewhere? site me some resources for sure ..