Sunday, September 25, 2011

How To Insert Data Into Mysql Database With PHP

Before learning how to insert data into mysql database, you need a little know sql and html language to facilitate you in understanding this. The first thing you should do is create the database.
This is an example database that we will use, copy and paste the sql code in the phpmyadmin sql box.



This is sql code
CREATE TABLE  `db_ilmubagus`.`account` (
`id` INT( 2 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 20 ) NOT NULL ,
`password` VARCHAR( 20 ) NOT NULL ,
`full_name` VARCHAR( 20 ) NOT NULL ,
`home_address` TEXT NOT NULL ,
`email_address` VARCHAR( 20 ) NOT NULL
) ENGINE = MYISAM ;
Then create a php file that serves to connect to the mysql database, the function of a separate connection file is much easier for us to call him if we need it,This is PHP code
<?php
$server = "localhost";
$user = "root";
$password = "root";
$database = "db_ilmubagus";

mysql_connect($server,$user,$password) or die ("Connection Fails");
mysql_select_db($database) or die ("Database Not Found");
?>
Save with the name koneksi.php
Now create a form like this

This is php code to create a form on top
<h2>Account</h2>
<hr />
<form action="insert_data.php" method="post">
<table border="0">
<tr>  <td>Username : </td>     <td><input name="username" type="text" /></td> </tr>
<tr>  <td>Password : </td>     <td><input name="password" type="password" /></td> </tr>
<tr>  <td>Full Name : </td>     <td><input name="full_name" type="text" /></td> </tr>
<tr>  <td>Home Address :</td>     <td><textarea class="25" name="home_address" rows="5"></textarea></td> </tr>
<tr>  <td>Email Address :</td>     <td><input name="email" type="text" /></td> </tr>
<tr>  <td><input type="submit" value="Save" /></td>     <td><input type="reset" value="Reset" /></td> </tr>
</table>
</form>
Form has been created, now create a php file with a name corresponding to the action form, is insert_data.php. Which serves to receive input form, type or copy the following code
<?php
//call file koneksi.php
include "koneksi.php";

mysql_query("INSERT INTO account(username,password,full_name,home_address,email_address)
       VALUES ('$_POST[username]','$_POST[password]','$_POST[full_name]',
         '$_POST[home_address]','$_POST[email]')");
?>
Try entering the data on the form, if the data has been entered on the database, you have succeeded.

1 comment:

sinidu said...
This comment has been removed by the author.