Skip to content
Advertisement

checking mysql error code to prevent deleting a parent key to a foreign key to alert user

I have a table named magazine, there is a foreign key from a table called researcher. I need to alert the user when they delete a researcher who has a magazine. I did that by using the mysql error code. this is my code.

elseif($_POST['submit'] == 'deleteresearcher'){
    // prepare sql and bind parameters
    $stmt = $conn->prepare("DELETE FROM `researcher` where id = $researcherid");
    $stmt->execute();
     // after executing the statement, check if there's an error.  
    if (mysqli_errno($conn) ==1051){ 
        echo "<script type='text/javascript'>alert('Sorry, can't delete researcher.');</script>";
      }
     // adding action 
    header("Location: admin_researcher.php?action=delete");    
}

P.S: the variable $conn is from the php file that connects with the database

Advertisement

Answer

You need to set the header() before ANY echo or other output, even before this elseif condition.

You should also enable error_reporting(1); in your PHP on the Development environment, to actually see any PHP errors… Basic troubleshooting.. or of course tail the error log.

I do not want to comment the usage of JS’s alert()

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement