Removing from the DB...

This is my first project with PHP and till this point I can’t say I’ve done horribly bad. How would I go about passing a variable to a custom function through a link? I’ll post my code so you can see what I mean. Also, if you see anything that’s an amateur thing to do let me know, the only way I can better myself is with criticism.
The link inside the table should send the ID to the remove_from_DB(). When I tested it, it removed everything in the DB.

[php]

<?php //setting DB variables $host = "localhost"; $user = "xxxxx"; $pass = "xxxxx"; $dbase = "test"; $conn = mysql_connect($host,$user,$pass) or die("Could not connect"); $db = mysql_select_db($dbase); $query = mysql_query("SELECT * FROM phones"); echo ""; echo ""; while( $row = mysql_fetch_array($query)){ echo ""; } echo "
ID Name Phone Notes
ID: " .$row['ID']. " " .$row['name']. " " .$row['phone']. " " .stripslashes($row['notes']). " Remove?
"; ?> <?php function remove_from_DB(){ echo $id; //setting DB variables $host = "localhost"; $user = "xxxxx"; $pass = "xxxxx"; $dbase = "test"; $sql = "DELETE FROM phones WHERE ID=$id"; //connecting to & setting the DB $conn = mysql_connect($host,$user,$pass) or die("Could not connect"); $db = mysql_select_db($dbase); //removing data mysql_query($sql); mysql_close($conn); } ?>

[/php]

You need to link to a php script, you cannot link to function. Have your link constructed like this:

[php]<a href=‘remove.php?id=".$row[‘ID’]. "’>Remove
[/php]

and then, create file named remove.php and put there this code:

[php]<?php

$id = (int)$_GET[‘id’];

// delete record from db
remove_from_DB($id);

// redirect back to main page
header(‘Location: index.php’);
exit;

function remove_from_DB($id){
//setting DB variables
$host = “localhost”;
$user = “xxxxx”;
$pass = “xxxxx”;
$dbase = “test”;
$sql = “DELETE FROM phones WHERE ID=$id”;

//connecting to & setting the DB
$conn = mysql_connect($host,$user,$pass) or die(“Could not connect”);
$db = mysql_select_db($dbase);

//removing data
mysql_query($sql);
mysql_close($conn);
}
?>
[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service