Impact of variable names in MySQL stored procedures on deletion operation

Encountering a puzzling issue with a MySQL stored procedure. Here is the procedure:

DROP PROCEDURE IF EXISTS `removeSubscription`;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `removeSubscription`(IN `userId` int,IN `channelId` int,IN `channelTypeTitle` varchar(255))

BEGIN

SET @userId = userId;
SET @channelId = channelId;
SET @channelTypeTitle = channelTypeTitle;

DELETE FROM subscriptions 
WHERE 
    userid = @userId AND 
    channelid = @channelId AND 
    channeltypeid = (SELECT id FROM channeltypes WHERE `name` = @channelTypeTitle) 
LIMIT 1;

END
;;
DELIMITER ;

Issue arises when calling this stored procedure from PHP; it ignores the 'WHERE' clause and deletes the first row encountered. Without 'LIMIT 1', everything in the table gets deleted :s

This is the PHP code being used:

$stmt = $db->prepare("CALL removeSubscription(:userId, :channelId, :channelTypeTitle)");

$stmt->bindValue('userId', $userId);
$stmt->bindValue('channelId', $channelId);
$stmt->bindValue('channelTypeTitle', $channelTypeTitle);

$stmt->execute();

Interestingly, renaming the passed parameters in both PHP's prepare statement and the Stored Procedure fixes the issue. Any obvious oversight on my end here?

Answer №1

Ensure that the names of variables are not reused within their scope and avoid using global variables inside stored procedures, as they have a global scope. Local variables should be used instead.

DROP PROCEDURE IF EXISTS `removeSubscription`;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `removeSubscription`(IN `userId` int, IN `channelId` int, IN `channelTypeTitle` varchar(255))

BEGIN

declare userId_, channelId_, channelTypeTitle_ integer;

SET userId_ = userId;
SET channelId_ = channelId;
SET channelTypeTitle_ = channelTypeTitle;

DELETE FROM subscriptions 
WHERE 
    userid = userId_ AND 
    channelid = channelId_ AND 
    channeltypeid = (SELECT id FROM channeltypes WHERE `name` = channelTypeTitle_) 
LIMIT 1;

END
;;
DELIMITER ;

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

Retrieving information from a database and displaying it in JSON format as a response

Within my MySQL table, I have a set of records that I would like to fetch and display in the format of a JSON response as shown below. "results":[ { "timestamp":"2014-03-04 17:26:14", "id":"440736785698521089", "category":"spo ...

We are unable to show the registration form error, and the input cannot be added to the mysql database

Apologies for any confusion caused by the presence of Malay language in my code. I hope that from looking at the code itself, you can understand the issue. The problem lies in error input not being displayed when entered, and if there are no errors, the da ...

If the value stored in $_SESSION['uname'] is not "teacher", redirect back to the homepage

I am currently working on a webpage and I want to restrict access to only users with the username "teacher". I came across this code snippet: <?php session_start(); if(!isset($_SESSION['uname'])){ header('location:(main p ...

Remove elements from JSON string created from a PHP array

In my code, there is a PHP function called $users->getFullUserList('json') which returns a JSON string containing user data. This data is created from a PHP Array using json_encode($this->userListArray) Before it is converted into a JSON s ...

The process of transferring SHA1 passwords created through PHP to Bcrypt in JavaScript

My journey into the realm of encryption is a bit new, and after spending a few days on this, I find myself in need of assistance. The goal is to email the users, have them log in, verify their password against SHA1, and then encrypt the provided password ...

The Prestashop feature RenderView within the backOffice Controller

Currently working on a Prestashop module, I found myself in need of a new controller. After creating it without any issues, I encountered some problems when trying to display information within it. The code snippet I have so far is as follows: class Pin ...

Implementing authentication in GuzzleHTTP Request Objects for improved asynchronous processing

In my project, I am generating multiple GuzzleHttp\Psr7\Requests as shown below: use GuzzleHttp\Psr7\Request; $myRequest = new Request( 'GET', $someUri ); All these requests are stored in an array called $guzzleRequ ...

"Enhance your Magento store with the ability to showcase multiple configurable products on the category page, even when dropdown values are not

As I work on adding multiple configurable products to a category list page in Magento 1.7.2, I am facing some challenges due to using the Organic Internet SCP extension and EM Gala Colorswatches. While following tutorials from various sources like Inchoo a ...

Fetch the count of files in a directory using AJAX

I'm attempting to fetch the number of files in a folder and compare it with the maxfiles value. Within dropzone.js, there is a function that looks like this: Dropzone.prototype._updateMaxFilesReachedClass = function() { if ((this.options.maxF ...

Confirm the authenticity of a Facebook page's URL

In the app I'm working on, users have the option to input a link to their Facebook Page (specifically page, not Profile or Group, only a Page). I am currently facing challenges in validating if the URL I receive (on the server-side with PHP) is a leg ...

Inquiring about using REGEX to extract text between delimiters

My PHP challenge involves extracting specific content from a string: $mail = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ef8fff5fbf3fff7f2def2fbb0f3fff7f2b0ebf5b0eafbedea">[email protected]</a>"; $rep = "le. ...

Is it possible to save CF7 form submissions as PHP variables for front-end use?

Seeking assistance as I've encountered a roadblock and have been searching for a solution for the past 5 hours. I've set up my CF7 form and implemented a function to store all fields as variables and display them in the error log, which is funct ...

After uploading the WordPress theme, the wp_enqueue_style() function fails to work properly

I recently developed a new WordPress theme and encountered an issue while trying to load specific stylesheets for my child sites using the is_page(array('')) function in my function.php file. Surprisingly, only the files that were added to all of ...

Obtaining the first element from an array or JSON object

Can someone help me extract the image value from an array or JSON data? I have a data structure that includes various values, but I am only interested in retrieving the image value. This is an example of what I'm currently getting: {"image_intro":" ...

Retrieving data from MySQL through AJAX does not yield any information

I have been following a tutorial from W3 schools on PHP and AJAX database. Majority of the content is working fine, however it seems that there is no data being retrieved from the MySQL database I created called "exercises" in the "exercisedb" database. B ...

PHP Content File for Dynamic Ajax Website

I recently came across a very informative article that discussed how to create crawlable and link-friendly AJAX websites using pushState. The author provided detailed instructions on the process, but left out a crucial detail - how to store data in a PHP f ...

Customizing Laravel API to handle 413 Payload Too Large response

I've been working on creating a file uploader in my Laravel API, but I'm facing an issue specifically when uploading large files. The response seems to be getting mixed up and I can't seem to figure out how to fix it. Here's a snapshot ...

a script in JavaScript that retrieves the selected value from a radio button box

I have an AJAX table where I need to highlight one of the rows with a radio box on the left side. However, I lack proficiency in JavaScript and would like assistance in retrieving the value of the radio box by its ID from this table once it has been select ...

The attempt to retrieve the desired date format using regular expressions was unsuccessful

I've been attempting to use a regular expression to extract dates from text details, but unfortunately, the expression I'm using doesn't return any results. Here's the PHP code snippet I have for extracting dates: <?php preg_match( ...

Tips for automating the activation of intents at specific scheduled times in Dialogflow

I'm attempting to automatically trigger intents in Dialogflow to obtain the user's contact details at a scheduled time. Is it possible to achieve this using JavaScript? If so, could you please provide the code? ...