Sunday, September 9, 2012

Insert Data into MySQL in Object Orient PHP


Insert Data into MySQL in Object Orient PHP 

Create table employee in oops database

CREATE TABLE IF NOT EXISTS `employee` (
  `ID` int(20) NOT NULL AUTO_INCREMENT,
  `Name` varchar(50) NOT NULL,
  `Surname` varchar(30) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Next create person php which we take as include file where contain class and variables that we are going to input as name and surname

<?php
class person
{
    var $surname;
    var $name;
    function set_surname($new_surname)
    {
        $this->surname=$new_surname;
    }

    function get_surname()
    {
        return $this->surname;
    }

    function set_name($new_name)
    {
        $this->name=$new_name;
    }

    function get_name()
    {
        return $this->name;
    }
}
?>


Then create the form to input data

NAME Surname<?php
 include 'person.php';
 ?>
 <html>
 <body>
 <form action="insert.php" method="post"/>
  NAME<input type="text" name="name" />
  Surname<input type="text" name="surname" />
  <input type="submit" value="submit">
  </form>
  </html>
    </body>

Next create insert.php which takes the information to MySQL table and write the data.
<?php
    include("person.php");
    $con = mysql_connect("localhost", "root", "");
    if (!$con)
    {
        die("couldn't connect ".mysql_error());
    }
    mysql_select_db("oops", $con);

    $person = new person;
    $person->set_name($_POST['name']);

    $person1 = new person;
    $person1->set_surname($_POST['surname']);


    $sql="INSERT INTO employee (ID,Name,Surname ) VALUES ('','".$person->get_name()."','".$person1->get_surname()."')";
    if (!mysql_query($sql, $con))
    {
    die('Error in inserting '.mysql_error());
    }

    ?>

No comments:

Post a Comment