Jump to content

Deleting from MySQL database


alexsmith2709

Recommended Posts

I've tried reading through some of the threads but couldnt understand some of them.

 

I've made a newsfeed script which works how i want it to. Now i want to add the function to delete a row from the database from an "admin panel" on the website.

 

So far i have this:

<?php
include("includes.php");

doConnect();

$get_news = "SELECT id, title, text, DATE_FORMAT(datetime, '%e %b %Y at %T') AS datetime FROM newsfeed ORDER BY datetime DESC";

$result= mysqli_query($mysqli, $get_news)
	or die(mysqli_error($mysqli));

while ($row = mysqli_fetch_array($result)) {
echo '<strong><font size="3">'. $row['title'] .' </font></strong><br/><font size="3">'. $row['text'] .'</font><br/><font size="2">'. $row['datetime'] .'</font><br/><br/><a href="delnews.php?del_id=' .$row['id']. '">
	<strong>DELETE</strong></a>';}
?>

then my delnews.php is:

<?php
include("includes.php");

doConnect();

$query = "DELETE FROM newsfeed WHERE id = "$_POST['id']""; 

$result = mysql_query($query); 

echo "The data has been deleted."; 

?>

I believe the problem is $_POST['id']. i've tried different things in there but none work. It displays the echo line but doesnt actually delete anything.

 

I am new to php so this may be a stupid mistake, but try and play nice!

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/225779-deleting-from-mysql-database/
Share on other sites

When you're passing values via HTTP (through a URL) you should be using GET not POST.  I would also recommend sanitizing your variables to prevent MySQL injections.

$id = mysql_real_escape_string($_GET['id']);
$query = "DELETE FROM newsfeed WHERE id = '$id'"; //if column id is an integer you don't need single quotes

 

Check out these links:

$_GET

$_POST

 

 

You aren't using POST when you append an argument to the URL, you're using GET. So, you'd need to use the value of $_GET['del_id'] to specify which record to delete. Your query string, as it currently is, will produce a parse error, and if you're trying to delete only 1 record, it's a good idea to limit the query to that . . .

$query = "DELETE FROM newsfeed WHERE id = " . $_GET['del_id'] . " LIMIT 1";

 

It would also be a good idea to validate the incoming data, and cast it as the appropriate type (I'm assuming integer).

if(!empty($_GET['del_id']) ) {
     $_GET['del_id'] = (int) $_GET['del_id'];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.