I have a table in which i want to insert multiple rows having values from a php array , now i can't figure out how to pass an array in stored procedure .
Example-: i have a php array having names ['sqlite','mysql','sql']
now what i want is to send this array to stored procedure and loop through the array taking one value at a time and inserting into the database table.
You can pass a string with your list and use a prepared statements to run a query, e.g. -
DELIMITER $$
CREATE PROCEDURE GetFruits(IN fruitArray VARCHAR(255))
BEGIN
SET #sql = CONCAT('SELECT * FROM Fruits WHERE Name IN (', fruitArray, ')');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
$$
DELIMITER ;
How to use:
SET #fruitArray = '\'apple\',\'banana\'';
CALL GetFruits(#fruitArray);
SELECT *
FROM fruits
WHERE FIND_IN_SET ( name, fruit_array );
Hope this will help you..
Another Solution:
Use foreach loop:
foreach(condition)
{
//Create insert query string
}
//insert query
//Execute Query
For more help paste code
Related
SELECT #a:= deger1 FROM iscilik1 WHERE Id=16;
ALTER TABLE iscilik1kisiler MODIFY COLUMN deger4 DECIMAL GENERATED ALWAYS AS (#a*deger3) STORED;
Hi everyone.I have a problem with this code and giving error like this;enter image description here
I could not find where is the problem.Thanks for everything have a good jobs.
SELECT CONCAT( 'ALTER TABLE iscilik1kisiler ',
'MODIFY COLUMN deger4 DECIMAL ',
'GENERATED ALWAYS AS (',
deger1,
'*deger3) STORED' )
INTO #sql
FROM iscilik1
WHERE Id=16;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DROP PREPARE stmt;
I want to loop through an associative array that represents a table's columns and values, and call a stored procedure on each iteration that will insert each value into its respective column. The assoc. array and loop looks like this:
public static function update(
int $auctionId,
string $title,
string $description
) : void
{
$new = [
'auction_title' => $title,
'description' => $description
];
foreach ($new as $columnName => $value) {
Database::conn()->callSP('sp_auctions_update', [$auctionId, $columnName, $value]);
}
}
The stored procedure looks like this:
DELIMITER $$
DROP PROCEDURE IF EXISTS sp_auctions_update $$
CREATE PROCEDURE sp_auctions_update(
IN auctionId INT UNSIGNED,
IN columnName,
IN value,
)
SQL SECURITY INVOKER
MODIFIES SQL DATA
BEGIN
UPDATE auctions SET #columnName=#value, WHERE id=#auctionId;
END $$
DELIMITER ;
Is this possible to do? Or is there a better alternative? Many thanks
do you know what the prepared statement would look like in this instance?
CREATE PROCEDURE sp_auctions_update(
IN auctionId INT UNSIGNED,
IN columnName VARCHAR(64),
IN `value` INT UNSIGNED
)
SQL SECURITY INVOKER
MODIFIES SQL DATA
BEGIN
-- Build SQL query text, insert column name from variable into it
SET #sql := CONCAT('UPDATE auctions SET ', columnName, '=? WHERE id=?;');
-- Reassign parameters values from local variables to user-defined ones
-- because local variables cannot be used in USING
SET #value := `value`;
SET #auctionId := auctionId;
-- Prepare and execute the query
PREPARE stmt FROM #sql;
EXECUTE stmt USING #value, #auctionId;
DEALLOCATE PREPARE stmt;
END
Alternatively you may concat ALL parameters values into the query text:
CREATE PROCEDURE sp_auctions_update(
IN auctionId INT UNSIGNED,
IN columnName VARCHAR(64),
IN `value` INT UNSIGNED
)
SQL SECURITY INVOKER
MODIFIES SQL DATA
BEGIN
-- Build SQL query text, insert parameters from variables into it
SET #sql := CONCAT('UPDATE auctions SET ', columnName, '=\'', `value`, '\' WHERE id=', auctionId, ';');
-- Prepare and execute the query
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
Caution.
The columnName parameter value is inserted into SQL query text as-is - so injection is possible. You must add the code which controls this parameter value. For example you may check that the column with provided name exists in table structure.
Another 2 parameters cannot be a source of injection due to their numeric datatype.
DROP FUNCTION IF EXISTS `opalv3`.`LineRecordTemp` $$
CREATE FUNCTION `opalv3`.`LineRecordTemp` ( TABLE_ID INT, COLUMN_DATA TEXT) RETURNS INT
BEGIN
SET #sql= NULL;
SELECT CONCAT('UPDATE TABLE SET c_name = \'',ATTR_DATA,'\' WHERE t_id =',TABLE_ID) INTO #sql;
PREPARE stmt FROM #sql ;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
RETURN 0;
END $$
I am getting the error "Dynamic SQL is not allowed in stored function or trigger"
Is there any way through which I can run the Dynamic query from the MYSQL function
I've been trying to find an answer to this question, but haven't found any definitive "yes" or "no" in all my research.
I'm running a simple MySQL query like this:
UPDATE item SET `score`=`score`+1 WHERE `id`=1
Is there a way for that query to return the updated value, instead of the number of rows affected? Just as a reference, I'm doing this in PHP, so the actual code looks like:
$sql = "UPDATE item SET `score`=`score`+1 WHERE `id`=1";
$new_value = mysql_query($sql);
//Unfortunately this does not return the new value
I know I could do a second query and just SELECT the value, but I'm trying to cut down on queries as much as possible. Is there a way?
You can do it with a stored procedure that updates, and then selects the new value into an output parameter.
The following returns one column new_score with the new value.
DELIMITER $$ -- Change DELIMITER in order to use ; withn the procedure
CREATE PROCEDURE increment_score
(
IN id_in INT
)
BEGIN
UPDATE item SET score = score + 1 WHERE id = id_in;
SELECT score AS new_score FROM item WHERE id = id_in;
END
$$ -- Finish CREATE PROCEDURE statement
DELIMITER ; -- Reset DELIMITER to standard ;
In PHP:
$result = mysql_query("CALL increment_score($id)");
$row = mysql_fetch_array($result);
echo $row['new_score'];
No, there's nothing like postgresql's UPDATE ... RETURNING output_expression in MySQL (yet?).
If you don't want to run another Query SELECT then here is another way to do it. I have modified Mr. Berkowski code for reference:
DELIMITER $$
CREATE PROCEDURE increment_score
(
IN id_in INT
)
BEGIN
set #newScore := null;
UPDATE item SET score = IF((#newScore := score+1) <> NULL IS NULL, #newScore, NULL) WHERE id = id_in;
SELECT #newScore;
END
DELIMITER ;
No you cant. You could make a function or stored procedure that could do the insert and return the updated value but that would still require you to execute two queries from within the function or stored procedure.
You can create a trigger, and you will know everything about the modifications.
The table[file_request ] structure:
user_id[INT] file_id[CHAR(10)] all_files
This is the SQL code which work fine in MySQL clien: I am using heidisql
DROP PROCEDURE IF EXISTS check_user_files;
DELIMITER \\
CREATE PROCEDURE check_user_files(IN p_user_id INT,IN p_file_id CHAR(10),IN p_all_files VARCHAR(500))
BEGIN
IF EXISTS(SELECT 1 FROM file_request WHERE user_id = p_user_id AND movie_id = p_file_id) THEN
UPDATE file_request SET `requring_date`=NOW(),`all_files`= p_all_files WHERE `user_id`=p_user_id AND `movie_id`=p_file_id;
ELSE
INSERT INTO file_request (`user_id`,`requring_date`,`movie_id`,`all_files`)
VALUES (p_user_id,NOW(),p_file_id,p_all_files);
END IF;
END \\
DELIMITER ;
CALL check_user_files('23','T40431284','07 08 10 11 13 14');
DELIMITER ;
CALL check_user_files('23','F87951','01 02 03');
And I trying to create and execute the SQL query from PHP [didn't work] :
// create the call procedure statements
foreach($fileData as $key=>$value){
$callSP .= "DELIMITER ; \n
CALL check_user_files('$userID','$key','$value');\n";
}
$insert_file_request_query = "DROP PROCEDURE IF EXISTS check_user_files;
DELIMITER \\\\
CREATE PROCEDURE check_user_files(IN p_user_id INT,IN p_file_id CHAR(10),IN p_all_files VARCHAR(500))
BEGIN
IF EXISTS(SELECT 1 FROM file_request WHERE user_id = p_user_id AND movie_id = p_file_id) THEN
UPDATE file_request SET `requring_date`=NOW(),`all_files`= p_all_files WHERE `user_id`=p_user_id AND `movie_id`=p_file_id;
ELSE
INSERT INTO file_request (`user_id`,`requring_date`,`movie_id`,`all_files`)
VALUES (p_user_id,NOW(),p_file_id,p_all_files);
END IF;
END \\\\
$callSP";
mysqli_query($conn,$insert_file_request_query);
The SQL query which created from PHP didn't work as in the MySQL client!?
So, how can I fix it!?
[update1]
I found that the SQL query must in the special format [ the formate which work fine in the MySQL client] or shouldn't work,I tried to copy and paste the query which echo from the PHP, the query code become one line and couldn't execute in MySQL client,too.
[update2]
The code of create store procedure will work fine when I execute it alone from PHP.I mean,I split the whole process into three parts and execute them one by one.
part1: drop the procedure if it was exists; [using mysqli_query()]
part2: create the procedure;[using mysqli_query()]
part3:call the procedure;[using mysqli_multi_query()]
$insert_file_request_query = '';
foreach($fileData as $key=>$value){
$insert_file_request_query .= "CALL check_save_file_request('$userID','$key','$value');";
}
mysqli_multi_query($conn,$insert_file_request_query);
And my final solution was to create the Store Procedure in MySQL and call it from the PHP.It works fine now.
Thank you very much!!
You can't combine multiple statements in mysqli_query. Split out the definition of the stored procedure from the CALLs to it. If that still fails, we'll need the full and exact error message that you receive.