Hello! Good day everyone. Today, I will present the ” Simple Edit Data Using PHP and MYSQL [Responsive Page] “ to enable beginners to solve when they encounter “Deprecated: mysql_connect(): The MySQL extension is deprecated and will be removed in the future: use mysqli or PDO”. We use MYSQLi in constructing our SQL.
- First, create a database, name it as “simple”.
[sql]CREATE TABLE `names` ( `name_id` int(11) NOT NULL, `first_name` text NOT NULL, `middle_name` text NOT NULL, `last_name` text NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1;[/sql]
- Create a “connection.php” file. Then put the following codes.
[php]<?php
$mysqli = new mysqli(‘localhost’, ‘root’, ”, ‘simple’);
?>[/php]
- On the “index.php” file, put the following codes.
[php]<?php
include ‘connection.php’;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
<title>Edit Data From Database</title>
</head>
<body>
<?php
if (isset($_GET[‘action’])) {
if ($_GET[‘action’] == “edit”) {
$id = $_GET[‘id’];
$get_data = $mysqli->query(“SELECT * FROM names WHERE name_id = $id”);
$getData = $get_data->fetch_assoc();
?>
<br>
Edit:<br>
<form method=”post” action=”edit.php?id=<?php echo $id; ?>”>
First Name:<br>
<input type=”text” name=”fname” value=”<?php echo $getData[‘first_name’] ?>” /><br><br>
Middle Name:<br>
<input type=”text” name=”mname” value=”<?php echo $getData[‘middle_name’] ?>” /><br><br>
Last Name:<br>
<input type=”text” name=”lname” value=”<?php echo $getData[‘last_name’] ?>” /><br><br>
<button type=”submit” name=”edit”>Edit</button> <a href=”index.php”>Cancel</a>
</form>
<?php }
}
?>
</body>
</html>
[/php]
[php]if(isset($_GET[‘action’])) { statement.. }[/php]
The “isset($_GET[‘action’])” statement means that if the action has been triggered, the condition statement will function. It can be seen on the URL when the edit link has been triggered. The URL goes like this “index.php?action=edit”
Under the “isset($_GET[‘action’])” is the another condition which is the if($_GET[‘action’]==”edit”) . Meaning if the value of the action is equal to edit, the edit form will appear.
Last, create an “edit.php” file then put the following codes.
[php]
<?php
include ‘connection.php’;
if (isset($_POST[‘edit’])) {
$id = $_GET[‘id’];
$fname = $_POST[‘fname’];
$mane = $_POST[‘mname’];
$lname = $_POST[‘lname’];
$edit = $mysqli->query(“UPDATE names SET first_name = ‘$fname’, middle_name = ‘$mane’, last_name = ‘$lname’ WHERE name_id = $id”);
if ($edit) {
header(“Location: index.php”);
} else {
echo $mysqli->error;
}
}
?>
[/php]