Lab 3.6 - DELETE - Code

-Update and delete data from a PHP script

Chapter 3 Main




<?php

require_once '../mainfunctions.php';
// connect to the database
$conn = createConn();

printHead("3", "Lab 3.6 - DELETE", "Update and delete data from a PHP script");


if (isset($_POST['confirmdelete'])) {
    // if SUBMIT BUTTON CLICKED 
    $eid = $_POST['eid']; //gather contents from 'eid'
    $query = "delete from Employee where EmployeeId=$eid"; //specify query terms
    mysqli_query($conn, $query) or die(mysqli_error($conn)); //form query

    if (mysqli_affected_rows($conn)>0) {
         //if something changed at database rows.......
        header("Location: 3.3.php?actionheadervardeletefrom3-6=deleted!!!&idheadervardeletefrom3-6=$eid"); 
        //send the header to 3-3 w/ actionHeaderVar=deleted!!! and idHeaderVar=$eid
        //for purpose of feedback/confirmation printout on 3.3
        exit();
    }
    
    //if NOTHING has changed
    echo "<p class='error'>Unable to update record</p>";
} 


else{ 

        //if BUTTON NOT CLICKED aka if URL DIRECTLY TO PAGE INSTEAD OF VIA LINK FROM 3.3
        if (!isset($_GET['idlinkvarfrom3-3'])){//if no id was passed in
            echo "<p class='error'>No Employee ID provided. This page is not designed to be accessed directly-  
            You should be routed here from 3.3 as the result of an update or deletion <br> <a href='3.3.php'>Return to display page.</a>";
        } 

    $eid=$_GET['idlinkvarfrom3-3'];
    $query = "Select * from Employee where EmployeeId = $eid";
    $result = mysqli_query($conn,$query);

    if (!$result) {
        die(mysqli_error($conn));
    }


    // check for results
    if (mysqli_num_rows($result)> 0) {
        // retrieve result row
        $row = mysqli_fetch_assoc($result);
        $firstname=$row['FirstName'];
        $lastname=$row['LastName'];
        $email=$row['Email'];
        $title=$row['Title'];
    } 

    else {
        echo "<p class='error'>Unable to retrieve employee $eid. <a href='labComp3-3.php'>Return to display page.</a>";
    }
    
}

////////////////////////////////////////////////////////////////// ^
//////////////////////////////////////////////////////////////////DOES NOT RUN 
?>



<p>Employee Information</p>
<p><?php 
echo 
"$firstname  $lastname 
<br>$title
<br>$email"; 
?></p>

<!--this form has one hidden field and one button, directs back to itself @3-6d.php-->
<form method="post" action="3.6-d.php">
<p>
<input type="text" name="eid" value="<?php echo $eid; ?>">
<!--set from 'hidden' to text' for debugging purposes-->
<input type="submit" name="confirmdelete" value="Confirm Delete">
</p>
</form>
<p>Return to <a href="3.3.php">Employee Display</a></p>


<?php 
printFootWithCodeExample('3.6-dcode.php');
?>




BACK