I am able to display an entire table of MySQL on my webpage.
but the problem is… it just display data.
I can’t edit, or delete the data.
to edit or delete… I have to go all the way to phpMyAdmin and do it there…
So I tried googling how to do it… and can’t find a good answer. I know it has something to do with “id”
Does anyone have a sample code how to do it ?
Example
mysql data row number 1 | delete | edit
mysql data row number 2 | delete | edit
mysql data row number 3 | delete | edit
Does each row in your table have some column which uniquely identifies it? That’s what the “id” usually is, and it makes creating an interface to edit/delete simple.
<?php
mysql_connect("localhost", "username", "password");
mysql_select_db("db_name");
if (!empty($_POST['action']) && $_POST['action'] == "delete") {
//Delete the row
$sql = "DELETE FROM table WHERE id = " . $_POST['id'];
mysql_query($sql) or die("Error occurred: " . mysql_error());
} else if (!empty($_POST['action']) && $_POST['action'] == "edit") {
//Redirect to the page to edit this row
header("Location: edit.php?id=" . $_POST['id']);
exit;
} else {
//Display all the rows
$sql = "SELECT * FROM table";
$result = mysql_query($sql) or die("Error! " . mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['name'] . ' ..etc.. | <a href="' . $_SERVER['PHP_SELF'] . '?action=delete&id=' . $row['id'] . '">delete</a> | <a href="' . $_SERVER['PHP_SELF'] . '?action=edit&id=' . $row['id'] . '">edit</a><br />";
}
}
?>
Example of edit.php:
<?php
//Note: $_GET['id'] is set by appending "id=#" to the URL in the previous page
if (!empty($_POST)) {
$sql = "UPDATE table SET name = '" . mysql_real_escape_string($_POST['name']) . "' WHERE id = " . (int)$_POST['id'];
mysql_query($sql) or die("Error! " . mysql_error());
}
$sql = "SELECT name FROM table WHERE id = " . (int)$_GET['id'];
$result = mysql_query($sql) or die("Error! " . mysql_error());
$row = mysql_fetch_array($result);
?>
<html>
<head>
<title>Edit Row</title>
</head>
<body>
<form action="edit.php" method="post">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
Name: <input type="text" name="name" value="<?php echo $row['name']; ?>" />
<br /><input type="submit" value="Save Changes" />
</form>
</body>
</html>