Monday, January 19, 2015

Connecting Database in PHP

කොහොමද කට්ටිය ගොඩ කාලෙකට පස්සෙ?


අපි අද බලමු කොහොමද MySQL database එකක් අපේ PHP page එකට connect කරගන්නෙ කියලා!


First of all  we have to start our Apache Server in WAMP or XAMP. මම හිතනව ඔයලා ඒක නම් දනටමත් දන්නවා ඇති කියලා. ;)

Now we have to create our basic PHP file and save it in the WAMP or XAMP.

In WAMP you have to save your PHP file in the "www" folder in WAMP folder in "C" directory.
In XAMP you have to save your PHP file in the "htdocs" folder in XAMP folder in "C" directory.

Now we have to create our database in MySQL, so you have to start the MySQL server in XAMP.



දැන් අපි අපේ database එක create කරමු. First of all we have to login to MySQL.

දැන් අපි බලමු කොහොමද command prompt එකෙන් MySQL login වෙන්නෙ කියල.



After typing and pressing Enter button in the command prompt you will be asked to enter a password. Just don't type anything! Just Press Enter Button.

දැන් ඔයලා MySQL වලට login වෙලා ඉන්නෙ.

-u root = root is the default user in MySQL.
-p = password for the user, but root does not have any password so we keep it blank.
-h = this is the host where the database is located. We use localhost because our database is located in our local machine.


We create database with the command:- CREATE DATABASE test123;

test123 කියන්නෙ අපි create කරන database එකේ name එක.

හරි දැන් අපේ database එක create වෙලා ඉවරයි.

Now we have to select our database using:- USE DATABASE test123;

හරි,දැන් අපි PHP පැත්තට හැරෙමු.

First of all we have to establish the connection with the database server. 

$host = "localhost";
$user = "root";
$password = "";

$conn = mysql_connect('$host','$user',$password');    //This will select and establish the connection to the database server
if(!$conn){ die("Could not connect :".mysql_error());}
else { echo "Connection established to the Server!"}

දැන් database server එකට connection එක establish වෙලා තියෙන්නේ.

Now we have to select our database to use.

$dbName = "test123";

mysql_select_db('$dbName','$conn') or die ("Can not select Database".mysql_error());

දැන් අපේ database එකට අපි connect වෙලා ඉවරය.


Die is a PHP function which we use to handle exceptions such as database unavailability. It will terminate the attempt and returns an error if the database in unavailable.


ඊළඟ post එකෙන් අපි database එකෙන් data retrieve කරන හැටි බලමු.


ගැටලු සඳහා පහතින් comment කරන්න.

No comments:

Post a Comment