Rabu, 09 Februari 2011

kode PHP untuk Create Read Update Delete - from scratch

kode ini sebenarnya telah tersedia di http://www.killersites.com/forums/topic/2282/basic-php-system-vieweditdeleteadd-records/

di tulis ulang hanya sebagai pengingat dan siapa tahu ada yang membutuhkannya

kode ini di tulis benar-benar dari dasar, perlu diketahui perkembanan sekarang, aplikasi kebanyakan ditulis mengunakan framework (eg: codeigniter, cakePHP, kohana etc. ) untuk mempermudah pengkodean, karena tiap-tiap framework tersebut memiliki modul2 yang membantu mempercepat penyelesaian pekerjaan, kira-kira mottonya don’t reinvent the wheel.

namun biasanya untuk mempelajari framework butuh efort yang besar juga, apalagi tiap2 framework mempunyai kegunaan/target yang berbeda. selain itu banyak sekali framework yang tersedia sekarang in.

namun jika masih membutuhkan mengkode PHP from scratch, ini contoh CRUD nya

SQL

jalankan ini untuk membuat database, jalankan di MySQL (anda bisa gunakan PHPMyAdmin )

CREATE TABLE `players` (
`id` tinyint(4) NOT NULL auto_increment,
`firstname` varchar(32) NOT NULL,
`lastname` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `players`
--

INSERT INTO `players` VALUES(1, 'Bob', 'Baker');
INSERT INTO `players` VALUES(2, 'Tim', 'Thomas');
INSERT INTO `players` VALUES(3, 'Rachel', 'Roberts');
INSERT INTO `players` VALUES(4, 'Sam', 'Smith');

untuk melakukan koneksi de database tersebut, buat file berikut ini, namun pastikan username dan password untukMySQLnya telah anda sesuaikan dengan database anda, bersama nama databasenya, simpan codenya dengan nama connect-db.php

/*
CONNECT-DB.PHP
Allows PHP to connect to your database
*/

// Database Variables (edit with your own server information)
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'records';

// Connect to Database
$connection = mysql_connect($server, $user, $pass)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());

?>

untuk membuat kode untuk melihat view dari datanya,gunakan kode berikut dan simpan dengan nama view.php

/*
VIEW.PHP
Displays all data from 'players' table
*/

// connect to the database
include('connect-db.php');

// get results from database
$result = mysql_query("SELECT * FROM players")
or die(mysql_error());

// display data in table
echo "";
echo "";

// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {

// echo out the contents of each row into a table
echo "";
echo '';
echo '';
echo '';
echo '';
echo '';
echo "";
}

// close table>
echo "
ID First Name Last Name
' . $row['id'] . '' . $row['firstname'] . '' . $row['lastname'] . 'EditDelete
";
?>

Add a new record






sedangkan kode untuk membuat data baru adalaha berikut, simpan dengan nama new.php

/*
NEW.PHP
Allows user to create a new entry in the database
*/

// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($first, $last, $error)
{
?>



New Record


// if there are any errors, display them
if ($error != '')
{
echo '
'.$error.'
';
}
?>



First Name: * " />

Last Name: * " />

* required







}

// connect to the database
include('connect-db.php');

// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));

// check to make sure both fields are entered
if ($firstname == '' || $lastname == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';

// if either field is blank, display the form again
renderForm($firstname, $lastname, $error);
}
else
{
// save the data to the database
mysql_query("INSERT players SET firstname='$firstname', lastname='$lastname'")
or die(mysql_error());

// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>

berikut simpan dengan nama edit.php untuk melakukan pengeditan pada data yang telah ada

/*
EDIT.PHP
Allows user to edit specific entry in database
*/

// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $firstname, $lastname, $error)
{
?>



Edit Record


// if there are any errors, display them
if ($error != '')
{
echo '
'.$error.'
';
}
?>


"/>

ID:


First Name: * "/>

Last Name: * "/>

* Required







}

// connect to the database
include('connect-db.php');

// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));

// check that firstname/lastname fields are both filled in
if ($firstname == '' || $lastname == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';

//error, display form
renderForm($id, $firstname, $lastname, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE players SET firstname='$firstname', lastname='$lastname' WHERE id='$id'")
or die(mysql_error());

// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{

// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM players WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);

// check that the 'id' matches up with a row in the databse
if($row)
{

// get data from db
$firstname = $row['firstname'];
$lastname = $row['lastname'];

// show form
renderForm($id, $firstname, $lastname, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>

dan yang terakhir, kode untuk menghapus dan simpan dengan nama delete.php

/*
DELETE.PHP
Deletes a specific entry from the 'players' table
*/

// connect to the database
include('connect-db.php');

// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get id value
$id = $_GET['id'];

// delete the entry
$result = mysql_query("DELETE FROM players WHERE id=$id")
or die(mysql_error());

// redirect back to the view page
header("Location: view.php");
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
header("Location: view.php");
}

?>

selesai, happy coding
Categories:

0 komentar:

Posting Komentar