The delete query in Mysql is not functioning properly on a lamp stack

I have been working on a project involving php. Throughout the process, all my queries have been executing smoothly. However, I encountered an issue when attempting to delete an object...

Below is my php code:

<?php
//delete item
if(isset($_GET['deletecat'])){
    $id_to_delete = $_GET['deletecat'];
    $sql = mysql_query("DELETE FROM `category` WHERE `Category_id`=$id_to_delete LIMIT 1") or die('Error: Could not delete.');
    }
    else{
    header('location: category.php');
    exit();
    }       
?>

After this code, I only receive an error message. The GET value seems to be correct. In phpmyadmin, the SQL runs without issues. However, there is a pop-up message that appears when attempting to delete an object. What steps can I take to resolve this?

Answer №1

There could be several layers where issues may arise: the database connection, the query itself, or the data being sent.

It's also important to note that not filtering for " and ' marks can lead to problems, and not ensuring that the id is a number may cause SQL failures.

To troubleshoot, consider adding diagnostics to your code to check what MySQL reports as the error, providing insight on how to resolve it.

While it is generally suggested to use the mysqli extension instead of mysql extension, below is sample code using the current extension you are utilizing.

I hope this guidance proves helpful!

<?php

    if ( isset($_GET['deletecat'])) {

        #dbh -> represents the database resource. 
        $dbh = mysql_connect()

        #mysql_connect returns false if unsuccessful. Capture the error and display it.
        if (!$dbh) {
            die("Could not connect to the database server: ".mysql_error()."\n");
            #if using mysqli, utilize mysql_connect_error() instead
        }

        #Use an escape function to prevent injection attacks.    
        $id_to_delete = mysql_real_escape_string($_GET['deletecat'],$dbh);

        #Ensure $id_to_delete is treated as a number in your SQL statement. I have corrected it below.
        $sql = "DELETE FROM `category` WHERE `Category_id` = '$id_to_delete' LIMIT 1");

        #Check if the query was successful.
        $result = mysql_query($sql,$dbh);

        #In case of failure, catch the error and display relevant information in a user-friendly manner.
        if (!$result) {
            $error=mysql_error($dbh);
            die ("Error: Could not delete '"
                 .htmlentities(print_r($_GET['deletecat'],true)).". Error: $error\n"
            );

       }

       #If no errors were encountered, proceed with redirecting.
       header('location: category.php');
       exit();
    }
?>

[1]: For cautionary notes, refer to http://php.net/manual/en/function.mysql-connect.php

Answer №2

It is important to always escape the GET variable first in order to prevent any SQL injection attacks, as mentioned by deceze. Additionally, it's crucial to recognize that the message provided by phpmyadmin serves as a confirmation for executing the delete query. One can utilize mysql_real_escape_string($value) for escaping purposes; however, it's worth noting that this function is deprecated and will soon be removed according to PHP vendor guidelines. Goodbye.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fetching data from an uploaded file and transmitting it to a specified URL

<? if(isset($_POST["submit"])) { $f_name = $_FILES["filetoupload"]["name"]; $f_tmp = $_FILES["filetoupload"]["tmp_name"]; $store = "uploads/".$f_name; if(move_uploaded_file($f_tmp,$store)) echo "file uploaded successfully"; echo"<br>"; ...

Are you familiar with the concept of using predefined tasks in PHP with Cron

Is there a way to run a scheduled script that posts new content to my website at various random times? I may need to post data on different days and times, such as Monday at 9am and Tuesday at midday. I was considering using a database to store each piece ...

Store the advertisement click into the database utilizing PHP, subsequently access the provided hyperlink

I am developing a custom WordPress widget that displays advertisements. I want to track clicks on these ads and store the data in a database. The database table for click tracking is already set up, and I have a function called f1_add_advert_click($advert ...

Can someone please help me understand what mistakes I'm making in my array manipulation within a foreach loop?

I have an array called $photos with the following data: Array ( [0] => Array ( [fileURL] => https://www.filepicker.io/api/file/UYUkZVHERGufB0enRbJo [filename] => IMG_0004.JPG ) [1] => Array ...

What is preventing the successful insertion of a JSON array into a SQL database?

I am facing an issue with inserting a JSON array into an SQL database. I have an HTML table that stores its data in a JavaScript array, converts it to a JSON array, and then sends it to a PHP file. However, when trying to insert this JSON array into the da ...

What could be causing the "class not found" error in Laravel 4.1 for a namespaced class?

Encountering a problem with Laravel 4.1 while following a tutorial series. Within the "app" directory, I have a folder named "Acme/Transformers" containing two classes: "Transformer.php" and "LessonTransformer.php". When attempting to access "LessonTransfo ...

I keep encountering the same issue every time I try to execute the npm run watch command. Does anyone have any suggestions on how to fix this?

When attempting to execute the command npm run watch, I encountered an error as shown below: ERROR Failed to compile with 1 errors2:50:28 PM This dependency was not found: * vue in ./resources/js/app.js To install it, you can run: npm install --save vue ...

Encountering a syntax error or access violation problem when creating a new table migration in Laravel

Within my Laravel application, I have created the following table migration: <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schem ...

Guide on utilizing ajax to post data when the URL parameter changes, all without refreshing the page

As the URL parameter changes, the values in my HTML also change. I am passing these values to a JSON file, but they are getting erased when the page refreshes due to the post request. I have attempted to use event.preventDefault(), however, it seems to n ...

Check to see if the date selected from the HTML5 date picker is in the past compared to the current date

When working with HTML, I have a task where I need to input a date (mm/dd/yyyy) using the new HTML 5 date picker: <input name="date" type="date"> My goal is to validate whether the date entered is older than today's date. $this_date = $_POST ...

Laravel Image Processing Extension by Intervention with GD Library Integration

Apologies if my question seems a bit unclear at first. I will do my best to provide as much detail as possible. Currently, I am in the process of developing a Laravel application and I am incorporating the Intervention Image Facade. However, when attempti ...

Using PHP's mysqli function to generate a JSON array

Currently, I am in the process of learning php/mysql to enhance a website that I am constructing. Initially, everything was functioning as intended but there were numerous vulnerabilities and security flaws with minimal error handling mechanisms. To addres ...

Conceal the cancellation button on the 20th and the 3rd day of each month for Woocommerce Subscriptions

Currently, I am working on customizing Woocommerce Subscriptions for a specific product (ID:1812). In the code snippet below, I have successfully hidden the 'cancel' and 'reactivate' buttons for that product. However, my goal now is t ...

The ajax call functions successfully on both local endpoints and Linux servers, however, it fails to execute on Azure servers despite returning a 200 status code

I am facing an issue with an ajax call that is working fine locally and on Linux servers, but not on Azure. The HTTP status is 200 in all environments, including Azure. The PHP directory is located in a virtual directory on Azure. Any assistance with this ...

Performing a jQuery AJAX POST request to a non-SSL page from a secure SSL page

Here's the scenario: An HTTPS / SSL page Using jQuery A form being submitted via Ajax to a non-SSL page I'm not receiving any useful response. The same situation, but from non-SSL to non-SSL works perfectly. I can see my console log, but I&a ...

What is the best way to run an external JavaScript file at regular intervals?

I enjoy loading an external JavaScript file every 10 seconds, or whenever the page body is clicked (in which case, the script should only run if a few seconds have passed). If you could provide me with some documentation on this topic, that would be grea ...

CodeIgniter - Utilizing quotes within a form

Consider a scenario where the database has a field named NAME which contains text with both single and double quotes: TEST1 "TEST2" 'TEST3' Now, if you want to edit this value using the following code in a form: <label for="name">Ful ...

extracting information from an array using json parsing in php

I am currently facing an issue with decoding and parsing JSON values from an array. I seem to be struggling with getting it right. Here is the information provided: $send[0] : Array ( [0] => {"message-count":"1","messages":[{"error-text":"Missing to p ...

"Exploring the concept of a two-dimensional $_SESSION array in

In the process of creating a server-side workers manager script, I have encountered a challenge with managing multiple instances in the same browser. Currently, each instance saves job data in $_SESSION and calls itself with the next task to be completed. ...

HTML5 - Ajax - puzzling behavior that I am unable to comprehend

Need Help Clarifying My Issue: I currently have a Div with Page 1 content. Page 1 contains a button that transitions the div content to Page 2. Page 2 has a button that switches the div content back to Page 1. The Problem: If Page 1 is loaded first, t ...