Wednesday 17 October 2018

Edit Data: MYSQLI CRUD OOP Series

Data can be updated in the database by calling its id, and the matching data to it. In this step, the index.php file will be rewritten. We need to write algorithm for editing and edit web form for treating data for editing.

Step 7. Create an “Edit Controls
and Web Form Elements”
Rewrite your index.php under Step 3 into this.
<?php
if (isset($_REQUEST['edit'])){
$ul_id = $_REQUEST['edit'];
$edit = $obj->display_selected_userlevel($ul_id);
?>
<!--Edit Data Form-->
<form action="<?php echo $_SERVER['PHP_SELF'];?>?edit=<?php echo $_GET['edit']; ?>" method="post">
<table align="center">
<tr>
<td colspan="2">
<?php if (!empty($errors)): ?>
<strong>Oops!</strong><?php echo implode('', $errors); ?>
<?php endif; ?>
</td>
</tr>
<tr>
<td colspan="2">
<?php if (!empty($success)): ?>
<strong>Good!</strong><?php echo implode('', $success); ?>
<?php endif; ?>
</td>
</tr>
<tr>
<td colspan="2"><input type="text" name="ulevel_name" value="<?php echo $edit['ulevel_name'];?>"></td>
</tr>
<tr>
<td colspan="2"><input type="text" name="ulevel_desc" value="<?php echo $edit['ulevel_desc'];?>"></td>
</tr>
<tr>
<td><input type="submit" name="edit_data" value="Update Data"></td>
<td><a href="<?php echo $_SERVER['PHP_SELF']; ?>">Return to List</a></td>
</tr>
</table>
</form>
<?php
}
else{
?>
<!--Save Data Form-->
<form action="index.php" method="post">
<table align="center">
<tr>
<td colspan="2"><?php
if(!empty($errors)){
echo "<strong>Oops!</strong>";
echo implode('', $errors);
}
if (!empty($success)){
echo "<strong>Good!</strong>";
echo implode('', $success);
}
 ?>
</td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="ulevel_name" placeholder="Username here"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="ulevel_desc" placeholder="Description here"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>
<?php 
}
?>

Add the following codes to class.functions.php to capture the data from database to the Edit Web Form Elements.

public function display_selected_userlevel($ul_id){
$sql=mysqli_query($this->con,"SELECT * FROM tbl_userlevel WHERE ulevel_id='$ul_id'");
//$row = mysqli_fetch_array($sql,MYSQLI_ASSOC);
$row = $sql->fetch_assoc();
return $row;
}

Discussion: The code has changed to cater the edit functionality.
if (isset($_REQUEST['edit'])){ This was set to be the default condition to check if the page is on editing data or on saving data operation. The web form element for saving data was placed under else statement since the page will load first with no interaction from the user.

//$row = mysqli_fetch_array($sql,MYSQLI_ASSOC);
$row = $sql->fetch_assoc();
The above-mentioned codes perform the same operation of retrieving data from database, it only differ on the use of format from OOP and procedural.

0 comments:

Post a Comment

If possible, leave a positive comment. No hate speech or elicit comments. Thank you.