Friday, December 13, 2013

Tute 8 : Connect Database in index.php file

Last tutorial we create database in mysql database. This tutorial we connect database with webpage.

Open our notepad++ software. Take a new document (Ctrl+N). Write is code in this new page :


---------------------------------------------------------------------------
<?php
$host='localhost';
$user='root';
$password= '';
$database='tutedb';

if (mysql_connect($host, $user, $password) or die()) {
     If(mysql_select_db($database)) {
      }
echo "OK";
} else{
echo "some error please check the code.";
}
?> ------------------------------------------------------------------------------

First line is php starting tag and last line php ending tag. If we will write php code always write starting and ending tag.
Our hostname is “localhost”, user is “root”, password is blank. And database name is tutedb. So we write this. If we will create password we write our password.
Next line we create if condition and connect the host. Then again create if condition and select our database.

We write here "if condition". If all operation successful publish "OK" otherwise publish "SOME ERROR. PLEASE CHECK THE CODE."

Now save this file. We save this file in our “tute” folder. We write file name “connect.inc.php”.

Connect Database in Website



Now we open the Google Chrome and take a new tab. Write in address bar “localhost/tute/connect.inc.php”.

We see OK in our window.


Connect Database in my website


If see other information our connect.inc.php files code has been problematic. Check and double check the code. Write the code correctly and refresh the Google Chrome “localhost/tute/connect.inc.php” page.


Now we go to our index.php file in notepad++ soft. We write this code in top of the file.

------------------------------------------------
<?php
require 'connect.inc.php';
?>
------------------------------------------------

Database connect to Site via require



In this code we import the connect.inc.php file in index.php file.
Save the file and again go to the Google Chrome and open index.php tab. Then refresh the page. In top line we see OK. We were successful!
If not see “OK” please check the php code.


After completing the connecting page we edit some code in connect.inc.php file. We cancel the if else condition. Our new code is :

-------------------------------------------------------------
mysql_connect($host, $user, $password) or die();
mysql_select_db($database);
------------------------------------------------------------

Then save the file.

No comments :

Post a Comment