Question about Unlink command

Is there an easier way of writing this code?
To get it to do the same thing but less scripting?

// get value of id that is sent from address bar 
$id=$_GET['id'];

// First query - unlink media file from subdirectory
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$target="../mp3/";
$file=$rows['file'];
$path="$target$file";
unlink($path);

There are some things that could be done with less scripting, yes. The question you should ask yourself, is: will it make the code more maintainable? Better readable? Safer?

[code]// get value of id that is sent from address bar
$id = intval($_GET[‘id’]);

// First query - fetch file name
$sql = “SELECT file FROM “.$tbl_name.” WHERE id=”.$id;
$result = mysql_query($sql) or die("SQL Error: ".mysql_error());

if (mysql_num_rows($result) > 0) {
$rows = mysql_fetch_array($result);

// Unlink media file from subdirectory
$path = “…/mp3/”.$rows[‘file’];
unlink($path);
}[/code]

Thank you for helpig me out. I learned a lot from your code example.
Just for my curiosity and learning what is the difference with:

$id = intval($_GET[‘id’]);
and
$id = $_GET[‘id’];

???

intval() returns the integer (numerical) representation of the parameter. It ensures that the value of $id is a number, and not a string (for example: “0; DELETE FROM tablename”). It has to do with checking user input for any malicious values.

Thank you again… I am so amazed with php programming. Thanks for teaching me about intval().

Better bookmark php.net. You’ll be using it often.

Sponsor our Newsletter | Privacy Policy | Terms of Service