How To Create Database Connection with PHP

12:03 AM

I am still learn abou PHP programming, on this post i want share with you how to create database connection with php. With this connection, you can use to modify database with your php script. Let start simple tutorial create connection between php / website with database.

Create Database Connection with PHP

Let start with running localhost server, i am using Lampp on ubuntu. If you don't know, just follow my older post about how to install lampp on ubuntu. You can start lampp with this command on terminal
sudo /opt/lampp/lampp start
After the server running, open the phpmyadmin to create the database. You must set the database first before creating connection with it.

Create Database with phpMyadmin

After your server running, just open localhost/phpmyadmin to access database control panel. Create database on database menu. For example i am using mmbasik database.
Create Database
Create Database


Create New User on Database

You can using default user root on the database, but i prefer to create user that only for this database. Administration user for one database. Open previlege menu to create new user role for new database that we've create on last step. Iam using simple password for testing

create user on database
create user on database

After creating database, its time to create connection between database and php script.

Create Connection to Database

On this post I just focus on creating connection to database, so i let my database empty. If you want input some data on database, feel free.

Let start copying the script below and save with .php extension. for example (connection.php)
<?
mysql_connect("localhost","databaseusername","databasepassword");
$conn=mysql_select_db("databasename");
if($conn){
 echo "connect";
}else{
 echo "disconnect";
}>


After creating the script below, don't forget to place the script on the htdocs / www folder. If you are using xampp, the folder name is htdocs that place on /opt/lampp/htdocs. 

Now lets runt the script on the browser with typing this address
http://localhost/connection.php

If your username, password and database name is correct you will get connect message. If what your enter on the that script is wrong, you will get disconnect message.

I hope you can use following this tutorial, if you have any question feel free to ask me on this comment section :)

Best Regrads

You Might Also Like

0 comments

Popular Posts

Subscribe