Hi friends to day i am going to tell you about something about PHP and MySQL. We all know that PHP is a one of best scripting language for web development.We can build awesome dynamic web pages using PHP.But we must build something valuable other than produce unimportant web sites. So today i am going to tel you how to write and test the OOP based connection class to MySQL database using PHP.
<?php /** * @author damith * @copyright 2011 */ class createConnection //create a class for make connection { var $host="localhost"; var $username="username"; // specify the sever details for mysql Var $password="password"; var $database="database name"; var $myconn; function connectToDatabase() // create a function for connect database { $conn= mysql_connect($this->host,$this->username,$this->password); if(!$conn)// testing the connection { die ("Cannot connect to the database"); } else { $this->myconn = $conn; echo "Connection established"; } return $this->myconn; } function selectDatabase() // selecting the database. { mysql_select_db($this->database); //use php inbuild functions for select database if(mysql_error()) // if error occured display the error message { echo "Cannot find the database ".$this->database; } echo "Database selected.."; } function closeConnection() // close the connection { mysql_close($this->myconn); echo "Connection closed"; } } ?>
OK.. Now you have create the connection class and now you can call this class inside your project. To test the connection i will get another PHP file and create a object from my existing connection class.. see below code how i am going to do it..
<?php include ('connection.php'); $connection = new createConnection(); //i created a new object $connection->connectToDatabase(); // connected to the database echo "<br />"; // putting a html break $connection->selectDatabase();// closed connection echo "<br />"; $connection->closeConnection(); ?>
I think you know how to test this.Start wamp server and goto your local host’s folder and test it.. If you success you can see the below message on a browser
Now you have connected to the MySQL friends.. see you in next post