Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

Form to delete data from MySQL database using PHP

So I'm creating a small program with 2 forms, one to add data to a database, and one to delete from it. I've managed to create the first input form, but I'm slightly confused as to how I would get the second form to work. In the database "tasks" I have a table called "ID" which has the columns "ID", "Name" and "Hours"

Here's what the two HTML forms look like

<h2>Add Tasks</h2> 
<form action="test.php" method="get">
Name of Task: <input type="text" name="name"><br />
Hours: <input type="number" name="hours"><br />
<input type="submit" value="Add" name="submit">
</form>

<h2>Delete Tasks</h2> 
<form action="delete.php" method="get">
ID: <input type="number" name="ID"><br />
<input type="submit" value="Delete">
</form>

And the PHP for the first form "Add tasks" which inserts data

$servername = "localhost";
$username = "root";
$password = "root";


$conn = new mysqli($servername, $username, $password, "Tasks");


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
};


if (isset($_GET['submit'])) {

mysqli_select_db ($conn,"Tasks");
$name = $_GET['name'];
$hours = $_GET['hours'];

$sql = "INSERT INTO ID (Name, Hours) VALUES ('".$name."','". $hours."')";
$results = mysqli_query($conn,$sql);


$query = "SELECT `Name` FROM `ID`";
$result = mysqli_query($conn, $query);
$x=0;

And the PHP for the second form which deletes tasks. This is the part that is not working

if (isset($_GET['submit'])) {
mysqli_select_db ($conn, "Tasks");
$id = $_GET['id'];
$sql = "DELETE FROM ID (ID) VALUES ('".$id."')";

$query = "SELECT `Name` FROM `ID`";
$result = mysqli_query($conn, $query);
$x=0;

How should I format the PHP for the second button. I've basically reused the code for the first form. Do I need to differentiate it somehow from the first button? Currently the page is showing up completely blank. I'm a complete novice so any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your SQL Statement

"DELETE FROM ID (ID) VALUES ('".$id."')"

is wrong.

It should be

DELETE FROM table_name
WHERE some_column=some_value;

. So, change your statement to

DELETE FROM ID WHERE ID='$id'

Suggestions

  • You should use POST method for action which will result in data edit.
  • You should check the input, make sure it did not contain SQL statement. A good way is to use $stuff = mysql_real_escape_string($_GET["stuff"]).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...