Link to home
Start Free TrialLog in
Avatar of Opeyemi AbdulRasheed
Opeyemi AbdulRasheed

asked on

Avoid Updating to Existing Data

While updating a particular user, I don't want user to update Username to an existing one so I assigned a Unique Key to a field (Username) in Users table to prevent duplicates, so, I like to output the Error message to the user on modal.

How can I trap that error and where to put it in the following script?
<?php

if ( ! empty($_POST) ):

    include('../includes/connection.php');

// Let's see if we have values
    if(!isset($_POST['newSubject'])) { $_POST['newSubject'] = array(); }
    if(!isset($_POST['newClass'])) { $_POST['newClass'] = array(); }
    
    $missingSubjects = count( array_filter($_POST['subject_taught'], function($i) { return $i == ''; }) );
    $missingClasses = count( array_filter($_POST['class_taught'], function($i) { return $i == ''; }) );
    $missingNewSubjects = count( array_filter($_POST['newSubject'], function($i) { return $i == ''; }) );
    $missingNewClasses = count( array_filter($_POST['newClass'], function($i) { return $i == ''; }) );

    if ( empty( $_POST["initial"] ) || empty( $_POST["username"] ) || empty( $_POST["password"] ) || empty( $_POST["role"] ) || $missingSubjects || $missingClasses || $missingNewSubjects || $missingNewClasses ):

        $update_err = "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
        <span class='badge badge-danger'>Required</span> You must fill in all fields.
        </div>";
        $response = array( 'success' => false, 'message' => $update_err );
        die( json_encode($response) );
        
    endif;

    $newSubClass = $conn->prepare( "INSERT INTO UserClass (UserId, SubjectTaught, ClassTaught) VALUES (?, ?, ?)" );
    $newSubClass->bind_param( "iss", $userId, $newSubject, $newClass );


    $userSubClass = "UPDATE UserClass SET SubjectTaught = ?, ClassTaught = ? WHERE UserClassId = ?";
    $result = $conn->prepare($userSubClass);
    $result->bind_param("ssi", $subject, $class, $userClassId);
        
    $sqlStr = "UPDATE Users SET Initials = ?, Username = ?, Password = ?, Role = ?, ClassAssigned = ? WHERE UserId = ?";
            $stmt = $conn->prepare($sqlStr);
            $stmt->bind_param("sssssi", $initial, $username, $password, $role, $class_assigned, $id);

            $initial = $_POST["initial"];
            $username = $_POST["username"];
            $password = $_POST["password"];
            $role = $_POST["role"];
            $class_assigned = $_POST['class_assigned'];
            $id = $_POST["user_id"];

        if ( $stmt->execute() ):

            foreach ($_POST['subject_taught'] as $userClassId => $subject):
                $class = $_POST['class_taught'][$userClassId];
                $result->execute();
            endforeach;

            if ( $result->execute() ):

                $userId = $_POST["user_id"];

                foreach ($_POST['newSubject'] as $key => $newSubject):
                    $newClass = $_POST['newClass'][$key];
                    $newSubClass->execute();
                endforeach;           

                $update_success = "<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
                  <span class='badge badge-success'>".$_POST["initial"]."</span> was successfully updated.
                  </div>";
                $response = array( 'success' => true, 'message' => $update_success );
                die( json_encode($response) );
        
            endif;

        endif;

endif;

?>

Open in new window

Thanks you
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Opeyemi AbdulRasheed
Opeyemi AbdulRasheed

ASKER

PS - You have an extra $result->execute() on line 52 (and a matching endif on line 67) of your code that doesn't look like it should be there
I thought I needed to put that there for the INSERT part.
Nope. If you look through your code, you have this:

$userSubClass = "UPDATE UserClass SET SubjectTaught = ?, ClassTaught = ? WHERE UserClassId = ?";
$result = $conn->prepare($userSubClass);

and then this:

foreach ($_POST['subject_taught'] as $userClassId => $subject):
    $class = $_POST['class_taught'][$userClassId];
    $result->execute();
endforeach;

So that will loop through all the subject_taught inputs and execute the UPDATE query for each.

If you then call $result->execute() again, all you're doing is running the last UPDATE query a second time. No need!
Quick as usual. Thank you sir