...

View Full Version : Php delete from a form



fireglow
11-22-2011, 08:32 PM
So im new to php and i cant figure out how to delete from a mysql table using a form. I found an insert script using a form, but i dont know how to change it for delete. Im sure it there staring at me, but i cant seem to figure it out.
Thanks for your help!

Adee
11-22-2011, 08:40 PM
post your code

fireglow
11-22-2011, 08:44 PM
here is the insert code,

html form


<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" value="ADD" />
</form>

php


<?php
$con = mysql_connect(*********);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("hey", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
Header("Location: users.html");

mysql_close($con);

?>

Adee
11-22-2011, 09:03 PM
and what exactly do you want to delete?

also, use mysql_escape_string() around any variables you are using with a database.

Here's a tip for your database design:
add an id field at the beginning of your table, and make it auto number. That way, if people have the same first and last name, you can delete only by their ID which will preserve the other data.

If you want to just do it with your current set up..



$firstname = mysql_escape_string($_POST['firstname']);
$lastname = mysql_escape_string($_POST['lastname']);

$query = "DELETE FROM Persons WHERE FirstName = '$firstname' AND LastName = '$lastname'";

mysql_query($query)

fireglow
11-22-2011, 09:14 PM
so this?


<?php
$con = mysql_connect("******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("hey", $con);

VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]');

$query = "DELETE FROM Persons WHERE FirstName = '$firstname' AND LastName = '$lastname' AND Age ='age'";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
Header("Location: users.html");

mysql_close($con);

?>

XterM
11-23-2011, 01:22 AM
add new field named "id" in your table bro. make it auto_increment. so, field in your table is: id, firstName, lastName, age.

then, just insert it like you do. the "id" will filled automatically, and this is uniq id.

then, select data from your table, and display it, and give a "delete" link with parameter id.




$sql = "select * from Persons order by id asc";
$sql = mysql_query($sql);
while($r = mysql_fetch_array($sql)){
echo $r[FirstName]." ".$r[LastName].". Age: ".$r[Age]." (<a href='delete.php?id=".$r[id]."'>delete</a>)<br>";
}



then, delete.php


$sql = "delete from Persons where id='".$_GET[id]."'";
$sql = mysql_query($sql);
if($sql){ echo "data deleted successfull"; }


hope it help



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum