What's new

Tutorial Create, edit, update and delete (crud) posts with mysql database php

saketnanga00

Addict
Joined
May 12, 2016
Posts
79
Reaction
64
Points
114
Hello dyan? Creating, editing, updating and deleting content on a website is what makes the site dynamic. At ayan ang gagawin natin para sa post na ito,.

Unang una gawa tayo ng database na papangalanan natin na CRUD, or kahit anong dbname na prefer nyo. then tutal halimbawa langnaman to lagyan natin ang table (table meaning ito yung mga nakapaloob sa database) na ito ng tatlong column.

id - int(11)
name - varchar(100)
address - varchar(100)

dalawang fields lang muna gawin lang muna natin itong simple at presentable para maintindihan ng lahat.

gawa tayo ng file index.php at sa loob nito ipaste nyo to:
<!DOCTYPE html>
<html>
<head>
<title>CRUD: CReate, Update, Delete PHP MySQL</title>
</head>
<body>
<form method="post" action="server.php" >
<div class="input-group">
<label>Name</label>
<input type="text" name="name" value="">
</div>
<div class="input-group">
<label>Address</label>
<input type="text" name="address" value="">
</div>
<div class="input-group">
<button class="btn" type="submit" name="save" >Save</button>
</div>
</form>
</body>
</html>

at dapat pag save neto at pagbukas mo sa browser ganto ang magiging resulta.

form_unstyled.png.2017-07-13.1499940749.png


Di maganda tignan diba? pagandahin muna natin, gawa tayo css file. yipi, pero bago yun ilagay mo muna sa head section ng index.php to

<link rel="stylesheet" type="text/css" href="style.css">

at kung nailagay mo na yan, gawa tayo ng file at style.css at ipaste mo to sa loob

body {
font-size: 19px;
}
table{
width: 50%;
margin: 30px auto;
border-collapse: collapse;
text-align: left;
}
tr {
border-bottom: 1px solid #cbcbcb;
}
th, td{
border: none;
height: 30px;
padding: 2px;
}
tr:hover {
background: #F5F5F5;
}

form {
width: 45%;
margin: 50px auto;
text-align: left;
padding: 20px;
border: 1px solid #bbbbbb;
border-radius: 5px;
}

.input-group {
margin: 10px 0px 10px 0px;
}
.input-group label {
display: block;
text-align: left;
margin: 3px;
}
.input-group input {
height: 30px;
width: 93%;
padding: 5px 10px;
font-size: 16px;
border-radius: 5px;
border: 1px solid gray;
}
.btn {
padding: 10px;
font-size: 15px;
color: white;
background: #5F9EA0;
border: none;
border-radius: 5px;
}
.edit_btn {
text-decoration: none;
padding: 2px 5px;
background: #2E8B57;
color: white;
border-radius: 3px;
}

.del_btn {
text-decoration: none;
padding: 2px 5px;
color: white;
border-radius: 3px;
background: #800000;
}
.msg {
margin: 30px auto;
padding: 10px;
border-radius: 5px;
color: #3c763d;
background: #dff0d8;
border: 1px solid #3c763d;
width: 50%;
text-align: center;
}



at isave.
dapat ganto magiging resulta nyan sa browser tada!

styled_form.png.2017-07-13.1499941037.png
I usually like to separate my HTML code from my PHP code as much as possible. I consider that good practice. On that note, let's create another file called php_code.php where we implement all php functionalities like connecting to the database, query the database and the like.

So open php_code.php and paste the following code in it:

<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'crud');

// initialize variables
$name = "";
$address = "";
$id = 0;
$update = false;

if (isset($_POST['save'])) {
$name = $_POST['name'];
$address = $_POST['address'];

mysqli_query($db, "INSERT INTO info (name, address) VALUES ('$name', '$address')");
$_SESSION['message'] = "Address saved";
header('location: index.php');
}

// ...

save again, then after nyan include natin sya sa taas ng index.php na file. like so :
<?php include('server.php'); ?>

At this point, all that this code does is connect to the database, initialize some variables and saves submitted data from the form to the database in the info we created earlier. That's only the CReate part of CRUD. Let's proceed with the others.

Now visit again your index.php file and add this code right under the <body> tag:

// ...
<body>
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>


so ang code na ito ay magdidisplay ng confirmation message kung may bagong record na nacreate sa ating database.

To retrieve the database records and display them on the page, add this code immediately above the input form:
<?php $results = mysqli_query($db, "SELECT * FROM info"); ?>

<table>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th colspan="2">Action</th>
</tr>
</thead>

<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['
name']; ?></td>
<td><?php echo $row['address']; ?></td>
<td>
<a href="index.php?edit=<?php echo $row['id']; ?>" class="edit_btn" >Edit</a>
</td>
<td>
<a href="server.php?del=<?php echo $row['id']; ?>" class="del_btn">Delete</a>
</td>
</tr>
<?php } ?>
</table>

<form>
// ...

then input tayo ng panibagong record at tignan kung gumagana ito:

address_saved.png.2017-07-13.1499944317.png



Mapapawow ka sa saya hahaha.

Ngayon naman editing stuff naman tayo.

At the top of your index.php file (immediately after the include statement) add the following code:

<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM info WHERE id=$id");

if (count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$name = $n['name'];
$address = $n['address'];
}
}
?>

When editting a database record, we need to put the old values in the form so that they can be modified. To do so, let's modify our input fields on the form and set those values taken from the database ($name, $address) as values to the value attribute of the form fields. gets mo? hahaha. intindihin mo yan as programmer kailangan malawak kaalaman natin lalo na sa pagingles.

tapos, gawa rin tayo ng hidden field na maghohold ng id natin para sa irerecord na data. hmm basta hirap explain. This explains it better:

// newly added field
<input type="hidden" name="id" value="<?php echo $id; ?>">

// modified form fields
<input type="text" name="name" value="<?php echo $name; ?>">
<input type="text" name="address" value="<?php echo $address; ?>">

Tandaan na ang lahat ng iyan ay nasa loob ng input <form>

Now if we click on the edit button on a particular record from the database, the values will be filled in the form and we will be able to edit them. Since we are editing on the same form as when we are creating, we have to put a condition that determines the appropriate button to be displayed. For example, when editing, we display the update button on the form and when creating, we display the save button. We do this using the update variable which is boolean. When update is true, the update button is displayed and if false, the save button is displayed.

Replace your save button on the form like this:

Replace ..

<button class="btn" type="submit" name="save" >Save</button>

with...

<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Save</button>
<?php endif ?>

at pag nirun natin ito, ito ang resulta nyan.

form_edit_state.png.2017-07-13.1499945404.png


Now you can see it is the update button that is displayed. Let's add the code that will be executed when this button is clicked.


Buksan ang php_code.php file and add this code at the button:

// ...

if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$address = $_POST['address'];

mysqli_query($db, "UPDATE info SET name='$name', address='$address' WHERE id=$id");
$_SESSION['message'] = "Address updated!";
header('location: index.php');
}


Now change the values in the form and click the update button.

record_updated.png.2017-07-13.1499945853.png

Nice one!


DELETING STUFF!

Just add this code at the end of you php_code.php file and you're good to go:

if (isset($_GET['del'])) {
$id = $_GET['del'];
mysqli_query($db, "DELETE FROM info WHERE id=$id");
$_SESSION['message'] = "Address deleted!";
header('location: index.php');
}

If you click the delete button, it deletes the record from the database and displays the message just like the other actions.

So ayun sana nakatulong ito. thanks!
 

Attachments

Last edited:
Query para sa pag create ng DB at table:
CREATE DATABASE `crud`;
CREATE TABLE `crud`.`info` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(100) NOT NULL , `address` VARCHAR(100) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;
 
Query para sa pag create ng DB at table:
CREATE DATABASE `crud`;
CREATE TABLE `crud`.`info` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(100) NOT NULL , `address` VARCHAR(100) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;
Yeah pwede yan, pero for beginners guide kaya ganun muna.
 
Newbie lang ts..ano pwede gamitin sa pagawa ng ganyan.? May software ba gagamitin? Salamat sa pag sagot:)
 
Last edited by a moderator:

Similar threads

Back
Top