I have table in SQL Server as below :
+--------------+----------------------------------------------+
| reportName | ShareWith |
+--------------+----------------------------------------------+
| IBM SH data | jack@gmail.com,alex@gmail.com,jan@gmail.com |
| Samsung Sr | alex@gmail.com,peter@gmail.com |
| Xiaomi MFG | |
| Apple US st | maria@gmail.com,alex@gmail.com |
| LG EU | fred@gmail.com |
+--------------+----------------------------------------------+
In my php file, I have an input text and a button. When a user type a report name and click on the button tt will perform an ajax call to remove the current user email from the selected report.
In SQL it should be as below :
select shareWith, UpdatedshareWith =
case
when shareWith like 'alex@gmail.com,%' then REPLACE(shareWith, 'alex@gmail.com,', '')
when shareWith like '%,alex@gmail.com,%' then REPLACE(shareWith, ',alex@gmail.com,', ',')
when shareWith like '%,alex@gmail.com' then REPLACE(shareWith, ',alex@gmail.com', '')
when shareWith = 'alex@gmail.com' then ''
else shareWith
end
from table
where reportName = 'xxxx';
I'm trying to apply it dynamically in PHP but couldn't make it work.
$('#button').on('click', function(){
var reportName = x;
var username = y;
$.ajax({
type: "POST",
url: "delete.php",
data: { reportName : reportName,
username : username },
success: function(data) { console.log(data); }
});
});
and delete.php as below :
$stmt = $conn->prepare("UPDATE table SET shareWith = CASE
WHEN shareWith like '?,%' THEN REPLACE(shareWith, '?,', '')
WHEN shareWith like '%,?,%' THEN REPLACE(shareWith, ',?,', ',')
WHEN shareWith like '%,?' THEN REPLACE(shareWith, ',?', '')
ELSE shareWith
END
WHERE reportName = ?");
$stmt->execute([$_POST['username'], $_POST['username'], $_POST['username'],
$_POST['username'], $_POST['username'], $_POST['username'], $_POST['reportName']]);
echo json_encode('deleted');
I believe there is a cleaner way to do it. Any suggestions please what should i change in my code ? Thank you very much.