0

I was wondering how to make my code less cluttered and more re-usable. I have seperate delete.php files for deleting specific data from pages. For example I have Genre,Platform and Customers.

Genre Delete

//get value of ?id= from the url $DeleteID = $_GET['id']; echo $DeleteID; require("connect.php"); //Linking $link = connectToDB(); //SQL Query $sql = "DELETE FROM Genre WHERE GenreID = ".$DeleteID; //Execute $result = $link->query($sql); //Check if ($link->affected_rows == 1) { header( "Location: genre.php" ); } else { echo "Didn't Work"; } 

Platform Delete

<?php session_start(); //get value of ?id= from the url $DeleteID = $_GET['id']; echo $DeleteID; require("connect.php"); //Linking $link = connectToDB(); //SQL Query $sql = "DELETE FROM Platform WHERE PlatformID = ".$DeleteID; //Execute $result = $link->query($sql); //Check if ($link->affected_rows == 1) { header( "Location: platform.php" ); } else { echo "Didn't Work"; } 

I wanted to know if it was possible for these to be made into 1 delete file that I can alter, or statement. The user is redirected to these pages through a button in a table, and it redirects to the delete page with the PK ID of the record.

2
  • 2
    Pass a second GET parameter that tells the script where to delete from - and then use that in a switch statement. And go read up on SQl injection, before you proceed. Commented Jun 1, 2017 at 14:57
  • Welcome to Stackoverflow, while this is a programming question it is somewhat outside of the scope of the questions we usually help with. Questions about code syntax and best practices are better asked on codereview.stackexchange.com Commented Jun 1, 2017 at 15:48

2 Answers 2

1

You could pass another variable into the URL to indicate what you want to be deleted (Genre, Platform, Customers, etc.).

Granted, it becomes very easy to create a mess of if/else statements, but it would keep all the functionality limited to one file.

Sign up to request clarification or add additional context in comments.

Comments

0

you could write a small helper function:

function deleteMe($link, $table, $id){ //SQL Query $id = intval($id); $sql = "DELETE FROM `$table` WHERE `{$table}ID` = ".$id; //Execute $result = $link->query($sql); return $link->affected_rows; } 

You could then include this on a single delete page and use it as needed, passing your table and id in with GET params.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.