Using OOP With PHP
IT kaunokhmer taken how to use OOP (Object Oriented Programming) language with PHP.
First, we create a new state called clsConnection.php It contains a Class clsConnection Connect to the Database Constructor need for it to Connect to the Database immediately when we create it as Object.
<?php define('hostname', 'your_host_name'); define('username', 'your_username'); define('password', 'your_password'); define('databaseName', 'your_database_name'); class clsConnection{ public function __construct(){ $conn=mysql_connect(hostname, username, password) or die('Error:' . mysql_error()); mysql_select_db(databaseName, $conn) or die('Error:' . mysql_error()); return $conn; } }?><?php require_once('clsConnection.php'); $conn=new clsConnection(); class clsItem{ public function __construct($value){ $result=mysql_query("INSERT INTO tableName (item) VALUES ('$value')"); } public function Show(){ $data=mysql_query("SELECT * FROM tableName"); while($rows=mysql_fetch_array($data)){ echo '<p>' . $rows['item'] . '</p>'; } } }?>Finally, we create a new state called Index.php for User Insert Data to the Database.<?php require_once('clsItem.php'); if(isset($_POST['submit'])){ $value=$_POST['txtitem']; $item=new clsItem($value); $item -> Show(); } ?><html> <head> <title>Basic OOP</title> </head> <body> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> <label>Item : </label> <input type="text" name="txtitem" /> <br /> <input type="submit" value="Submit" name="submit" /> </form> </body></html> 