Wednesday, September 28, 2011

Easily Update & Delete Data In Mysql Database Using PHP

We have learned how to insert data into mysql database, incomplete if we stop there, now we will learn to update and delete data in mysql database with php.

1. create lists of data, we will make a list like this
This is the php code to make an appearance as above

<?php
include "koneksi.php";

$data = mysql_query("SELECT * FROM account");
echo "<a href='form.php'>+ Add Account</a>
   <table border='1'>
  <th>No</th>
  <th>Username</th>
  <th>Password</th>
  <th>Full Name</th>
  <th>Home Address</th>
  <th>Email Address</th>
  <th>Acction</th>";
$no = 1;
while ($r=mysql_fetch_array($data)){
 echo "<tr>
   <td>$no.</td>
   <td>$r[username]</td>
   <td>$r[password]</td>
   <td>$r[full_name]</td>
   <td>$r[home_address]</td>
   <td>$r[email_address]</td>
   <td><a href='form_edit.php?id=$r[id]'>Edit</a> | <a href='delete_data.php?id=$r[id]'>Delete</a></td>
     </tr>";
     $no++;
 }
echo "</table>";
?>
save with the name list_data.php

2. Create a php file with the name form_edit.php, then type or copy the following code
<?php
include "koneksi.php";
$data = mysql_query("SELECT * FROM account WHERE id='$_GET[id]'");
$r=mysql_fetch_array($data);

echo "<h2>Edit Account</h2><hr>
<form method='POST' action='update_data.php'>
<input type='hidden' name='id' value='$r[id]'>
<table border='0'>
<tr>
 <td>Username : </td>
    <td><input type='text' name='username' value='$r[username]'></td>
</tr>
<tr>
 <td>Password : </td>
    <td><input type='text' name='password' value='$r[password]'></td>
</tr>
<tr>
 <td>Full Name : </td>
    <td><input type='text' name='full_name' value='$r[full_name]'></td>
</tr>
<tr>
 <td>Home Address :</td>
    <td><textarea name='home_address' class='25' rows='5'>$r[home_address]</textarea></td>
</tr>
<tr>
 <td>Email Address :</td>
    <td><input type='text' name='email' value='$r[email_address]'></td>
</tr>
<tr>
 <td><input type='submit' value='Update'></td>
</tr>
</table>
</form>";
?>
So when you click the edit link on the list will produce a display like this


3. Now we just create a php file to receive input from form_edit.php.
Create a file named update_data.php, then type or copy and paste the following php code on update_data.php
<?php
include "koneksi.php";

mysql_query("UPDATE account SET username = '$_POST[username]',
    password = '$_POST[password]',
    full_name = '$_POST[full_name]',
    home_address = '$_POST[home_address]',
    email_address = '$_POST[email]'
   WHERE id = $_POST[id]");
header ('location:list_data.php');
?>
We have completed the update of data, just one more thing that is delete the data,
we only need one php file again to delete the data, the usual type or copy and paste the following code, save with the name delete_data.php
<?php
include "koneksi.php";

mysql_query("DELETE FROM account WHERE id='$_GET[id]'");
header ('location:list_data.php');
?>
Done ... I hope to be useful

No comments: