Click here to Skip to main content
15,896,359 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When the user selects to delete a department or location, then the system should check against the database to see if that entry is used in other tables (ie personnel assigned to that department) and, if so, should prevent removal.

What's the best way to do it?

See my code:

HTML
<div class="col d-flex justify-content-center">

	<div class="btn btn-xs btn-primary5" id="confirmButton" style="display: inline; float: right;" onclick="toggleConfirmDep('Remove', 'removeDepartment()')"></div>

</div>


JavaScript
function removeDepartment() {

    let departmentName = $('#removeDepartmentDepartment').val()

    $.getJSON(`php/getAllDepartments.php`, function (departments) {

        let departmentID = departments.data.filter(dep => dep.name == departmentName)[0].id

        $.ajax({

            data: {
                'id': departmentID
            },
            url: 'php/deleteDepartmentByID.php', 
            dataType: 'json',

            success: function(data) {

                $('#removeDepartmentDepartment').find('option:eq(0)').prop('selected', true);
    
            }

        })

    }); 

}

function toggleConfirmDep(message, func) {
    
    if (!event) var event = window.event;
    event.cancelBubble = true;
    if (event.stopPropagation) event.stopPropagation();


    employeeID = $(event.target).closest(".buttons").siblings("form").find("#id").text();

    if ($('#confirmDep').css('display') == "none") {

        $('#confirmDep').show()
        $('#depQuestion').show()
        $('#depResponse').hide()

        let addOrRemove = capitalizeFirstLetter(message.split(" ")[0])
        addOrRemove == "Add" ? addOrRemove += "ed" : addOrRemove += "d"

        $('#depMessage').text(message)
        $('#depButton').attr('onClick', `
            ${func.toString()};
            $('#depQuestion').hide()
            $('#depResponse').show()
            $('#depResponseMessage').text('${addOrRemove}')
            setTimeout(function(){
                $('#confirmDep').hide();
                
                $('#profilePage').hide();
                
                window. location. reload(1);
                
            }, 1500);
            
        `)

    } else {
        
        $('#confirmDep').css('display', 'none')

    }

}


PHP
<?php

	// remove next two lines for production
	
	ini_set('display_errors', 'On');
	error_reporting(E_ALL);

	$executionStartTime = microtime(true);

	include("config.php");

	header('Content-Type: application/json; charset=UTF-8');

	$conn = new mysqli($cd_host, $cd_user, $cd_password, $cd_dbname, $cd_port, $cd_socket);

	if (mysqli_connect_errno()) {
		
		$output['status']['code'] = "300";
		$output['status']['name'] = "failure";
		$output['status']['description'] = "database unavailable";
		$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
		$output['data'] = [];

		mysqli_close($conn);

		echo json_encode($output);

		exit;

	}	

	// $_REQUEST used for development / debugging. Remember to cange to $_POST for production

	$query = 'DELETE FROM department WHERE id = ' . $_REQUEST['id'];

	$result = $conn->query($query);
	
	if (!$result) {

		$output['status']['code'] = "400";
		$output['status']['name'] = "executed";
		$output['status']['description'] = "query failed";	
		$output['data'] = [];

		mysqli_close($conn);

		echo json_encode($output); 

		exit;

	}

	$output['status']['code'] = "200";
	$output['status']['name'] = "ok";
	$output['status']['description'] = "success";
	$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
	$output['data'] = [];
	
	mysqli_close($conn);

	echo json_encode($output); 

?>


What I have tried:

I have tried the seal object assigned object database javascript but it does not work.
Posted
Updated 25-Feb-21 21:28pm
v2

1 solution

Use the FOREIGN KEY constraint[^] on the column definition, and SQL won't let you delete rows which are referenced by other tables - that's what it's there for!
 
Share this answer
 
Comments
farremireia 26-Feb-21 3:27am    
Thanks very much! I am very new into all these and not really sure I'm understanding how to use it.

I've updated the question so you can see my php and I was just wondering if, what I have to do is change the "$query = 'DELETE FROM department WHERE id = ' . $_REQUEST['id']" to the foreign key? Thank you! And please forgive my ignorance..
OriginalGriff 26-Feb-21 3:34am    
No, the FOREIGN KEY constraint is part of your database design, and is applied when you create of modify the table. Follow the link I gave you and it'll explain.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900