I have a simple question,
I have table:
| val | type | status |
|-----|------|--------|
| 90 | 1 | a |
i would like to have a stored proc that able to update above table based on variable given in input param.
for example, maybe in PHP i have array:
$data = ['val' => 80, 'status' => 'c']
i would like to send that data to mysql stored proc, so it'll knows that it need to update val to 80 and status into 'c'
or another example:
$data = ['type' => 1, 'nothing' => NULL, 'status' => NULL, 'val' => 77]
then it will update type to 1, status to null, val to 77 and ignore 'nothing'
*the $data input, shall not hardcoded in input param in Stored Proc :D
is this can be done 'simply' ?
Thanks!
Simple answer than a stored procedure :
<?php
$data = ['val' => 80, 'status' => 'c'];
function auto($x){
$field_string ='';
$input_string='';
foreach ($x as $userInfo=>$userInfo_value){
if($userInfo_value !=''){
echo $userInfo."->".$userInfo_value;
if ($field_string == '') {
$field_string = $field_string.$userInfo.' = '.$userInfo_value;
}
else {
$field_string = ','.$field_string.'='.$userInfo_value;
}
}
}
$sql = "UPDATE protocole_test SET ".$field_string."WHERE (condition not specified in question) ";
echo $sql ; //check query formed add a execution line after this
}
auto($data);
?>
Explanation :
Here we make a php function which handle your DATA ARRAY and form a dynamic update statement to update select fields with selected data.
Why not stored procedures ?
1) Stored procedures are stored in MYSQL engine
2) It cannot process DYNAMIC , VARIABLE LENGTH data arrays SIMPLY.
Still how to do procedural style :
Check out Passing string to Mysql Procedure.
Algorythem :
1) form a quamma seprated list like -> key,value,key,value with help of php as used in above php answer;
2) Call Procedure with QCM as parameter ;
3) Edit procedure to update fields (in answer insert operation is performed);
4)test.
Advantage of using php function :
1) Its simple . 2) it satify all purpouse of making a STORED PROCEDURE. 3) Its can also be called by ajax.
Thank you very much.