Skip to content
Advertisement

How to fix my CRUD not working in Update PHP MSQL

I tried to implement CRUD in m website but I am able to make Create, Read and Delete. However, something went wrong during developing the Update function. Can anyone help me? I will provide the code below. The code is used to update the users information if the logged in person is an Admin. Thank you.

<?php
// Include config file
require_once "config.php";

// Define variables and initialize with empty values
$firstname = $lastname = $email = $address = $status = $level = "";
$firstname_err = $lastname_err = $email_err = $address_err = $level_err = $status_err = "";

// Processing form data when form is submitted
if(isset($_POST["id"])){
    // Get hidden input value
    $id = $_POST["id"];

    // Validate name-first
    $input_firstname = trim($_POST["firstname"]);
    if(empty($input_firstname)){
        $firstname_err = "Please enter a first name.";
    } elseif(!filter_var($input_firstname, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Zs]+$/")))){
        $firstname_err = "Please enter a valid first name.";
    } else{
        $firstname = $input_firstname;
    }

    //Validate lastname
    $input_lastname = trim($_POST["lastname"]);
    if(empty($input_lastname)){
        $lastname_err = "Please enter a last name.";
    } elseif(!filter_var($input_lastname, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Zs]+$/")))){
        $lastname_err = "Please enter a valid last name.";
    } else{
        $lastname = $input_firstname;
    }

    //Validate email address
    $input_email = trim($_POST["email"]);
    if(empty($input_email)){
        $email_err = "Please enter an email address.";
    } else{
        $email = $input_email;
    }

    // Validate address 
    $input_address = trim($_POST["address"]);
    if(empty($input_address)){
        $address_err = "Please enter an address.";
    } else{
        $address = $input_address;
    }

    // Validate access level
    $input_level = trim($_POST["level"]);
    if(empty($input_level)){
        $level_err = "Please enter an level.";
    } elseif($input_level == 'Admin'){
        $level = $input_level;
    }elseif($input_level == 'Customer'){
        $level = $input_level;
    }else{
        $level_err = 'Please choose from Admin or Customer';
    }

    // Validate status
    $input_status = trim($_POST["status"]);
    if(empty($input_status)){
        $status_err = "Please enter a status";
    }elseif($input_status == '1'){
        $status = $input_status;
    }elseif($input_status == '0'){
        $status = $input_status;
    }else{
        $status_err = "Please enter a valid status";
    }
    

    // Check input errors before inserting in database
    if(empty($firstname_err) && empty($lastname_err) && empty($email_err) && empty($address_err) && empty($level_err) && empty($status_err)){
        // Prepare an update statement
        $sql = "UPDATE users SET firstname=?, lastname=? address=?, email=?, access_level=?, status=? WHERE id=?";

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "sssssii", $param_firstname, $param_lastname, $param_email, $param_address, $param_level, $param_status, $param_id);

            // Set parameters
            $param_firstname = $firstname;
            $param_lastname = $lastname;
            $param_address = $address;
            $param_email = $email;            
            $param_level = $level;
            $param_status = $status;
            $param_id = $id;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Records updated successfully. Redirect to landing page
                header("location: index.php");
                exit();
            } else{
                echo "Something went wrong. Please try again later.";
            }
            // Close statement
            mysqli_stmt_close($stmt);
        }else{
            echo mysqli_stmt_error($stmt);
        }
    }

    // Close connection
    mysqli_close($link);
} else{
    // Check existence of id parameter before processing further
    if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
        // Get URL parameter
        $id =  trim($_GET["id"]);

        // Prepare a select statement
        $sql = "SELECT * FROM users WHERE id = ?";
        if($stmt = mysqli_prepare($link, $sql)){

            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "i", $param_id);

            // Set parameters
            $param_id = $id;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                $result = mysqli_stmt_get_result($stmt);

                if(mysqli_num_rows($result) == 1){
                    /* Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop */
                    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);

                    // Retrieve individual field value
                    $firstname = $row["firstname"];
                    $lastname = $row["lastname"];
                    $email = $row["email"];
                    $address = $row["address"];
                    $level = $row["access_level"];
                    $status = $row["status"];
                } else{
                    // URL doesn't contain valid id. Redirect to error page
                    header("location: error.php");
                    exit();
                }

            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }

        // Close statement
        mysqli_stmt_close($stmt);

        // Close connection
        mysqli_close($link);
    }  else{
        // URL doesn't contain id parameter. Redirect to error page
        header("location: error.php");
        exit();
    }
}
?>

<?php
// core configuration
include_once "../../config/core.php";

// check if logged in as admin
include_once "../login_checker.php";

// set page title
$page_title = "Update Record";

// include page header HTML
include '../layout_head.php';

echo "<div class='col-md-12'>";

// get parameter values, and to prevent undefined index notice
$action = isset($_GET['action']) ? $_GET['action'] : "";

// tell the user he's already logged in
if ($action == 'already_logged_in') {
    echo "<div class='alert alert-info'>";
    echo "<strong>You</strong> are already logged in.";
    echo "</div>";
} else if ($action == 'logged_in_as_admin') {
    echo "<div class='alert alert-info'>";
    echo "<strong>You</strong> are logged in as admin.";
    echo "</div>";
}

echo "</div>";

//content when logged in
?>
<div class="wrapper" style="width: 500px; margin: 0 auto;">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="page-header">
                    <h2>Update Record</h2>
                </div>
                <p>Please edit the input values and submit to update the record.</p>
                <form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
                    <div class="form-group <?php echo (!empty($firstname_err)) ? 'has-error' : ''; ?>">
                        <label>First Name</label>
                        <input type="text" name="firstname" class="form-control" value="<?php echo $firstname; ?>">
                        <span class="help-block"><?php echo $firstname_err;?></span>
                    </div>
                    <div class="form-group <?php echo (!empty($lastname_err)) ? 'has-error' : ''; ?>">
                        <label>Last Name</label>
                        <input type="text" name="lastname" class="form-control" value="<?php echo $lastname; ?>">
                        <span class="help-block"><?php echo $lastname_err;?></span>
                    </div>
                    <div class="form-group <?php echo (!empty($address_err)) ? 'has-error' : ''; ?>">
                        <label>Email</label>
                        <input type="email" name="email" class="form-control" value="<?php echo $email; ?>" />
                        <span class="help-block"><?php echo $email_err;?></span>
                    </div>
                    <div class="form-group <?php echo (!empty($address_err)) ? 'has-error' : ''; ?>">
                        <label>Address</label>
                        <textarea name="address" class="form-control"><?php echo $address; ?></textarea>
                        <span class="help-block"><?php echo $address_err;?></span>
                    </div>
                    <div class="form-group <?php echo (!empty($level_err)) ? 'has-error' : ''; ?>">
                        <label>Access Level</label>
                        <input type="text" name="level" class="form-control" value="<?php echo $level; ?>">
                        <span class="help-block"><?php echo $level_err;?></span>
                    </div>
                    <div class="form-group <?php echo (!empty($status_err)) ? 'has-error' : ''; ?>">
                        <label>Status</label>
                        <input type="text" name="status" class="form-control" value="<?php echo $status; ?>">
                        <span class="help-block"><?php echo $status_err;?></span>
                    </div>
                    <input type="hidden" name="id" value="<?php echo $id; ?>"/>
                    <input type="submit" class="btn btn-primary" value="Submit">
                    <a href="index.php" class="btn btn-default">Cancel</a>
                </form>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Advertisement

Answer

<?php
// Include config file
require_once "config.php";

// Define variables and initialize with empty values
$firstname = $lastname = $email = $address = $status = $level = "";
$firstname_err = $lastname_err = $email_err = $address_err = $level_err = $status_err = "";

// Processing form data when form is submitted
if(isset($_POST["id"])){
    // Get hidden input value
    $id = $_POST["id"];

    // Validate name-first
    $input_firstname = trim($_POST["firstname"]);
    if(empty($input_firstname)){
        $firstname_err = "Please enter a first name.";
    } elseif(!filter_var($input_firstname, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Zs]+$/")))){
        $firstname_err = "Please enter a valid first name.";
    } else{
        $firstname = $input_firstname;
    }

    //Validate lastname
    $input_lastname = trim($_POST["lastname"]);
    if(empty($input_lastname)){
        $lastname_err = "Please enter a last name.";
    } elseif(!filter_var($input_lastname, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Zs]+$/")))){
        $lastname_err = "Please enter a valid last name.";
    } else{
        $lastname = $input_firstname;
    }

    //Validate email address
    $input_email = trim($_POST["email"]);
    if(empty($input_email)){
        $email_err = "Please enter an email address.";
    } else{
        $email = $input_email;
    }

    // Validate address 
    $input_address = trim($_POST["address"]);
    if(empty($input_address)){
        $address_err = "Please enter an address.";
    } else{
        $address = $input_address;
    }

    // Validate access level
    $input_level = trim($_POST["level"]);
    if(empty($input_level)){
        $level_err = "Please enter an level.";
    } elseif($input_level == 'Admin'){
        $level = $input_level;
    }elseif($input_level == 'Customer'){
        $level = $input_level;
    }else{
        $level_err = 'Please choose from Admin or Customer';
    }

    // Validate status
    $input_status = trim($_POST["status"]);
    if(empty($input_status)){
        $status_err = "Please enter a status";
    }elseif($input_status == '1'){
        $status = $input_status;
    }elseif($input_status == '0'){
        $status = $input_status;
    }else{
        $status_err = "Please enter a valid status";
    }
    
    echo "<script>alert('";
    echo "Checking all inputs vales---"; 
    echo $id; echo "=id--<br>";
    echo $input_firstname; echo "=fname---<br>";
    echo $input_lastname; echo "=lname---<br>";
    echo $input_email; echo "=email---<br>";
    echo $input_address; echo "=add---<br>";
    echo $input_level; echo "=level<br>";
    echo $input_status; echo "=stat<br>";
    echo "')</script> ";
    

    // Check input errors before inserting in database
    if(empty($firstname_err) && empty($lastname_err) && empty($email_err) && empty($address_err) && empty($level_err) && empty($status_err)){
        // Prepare an update statement
            echo "<script>alert('";
            echo "Im inside `Check Inputs before inserting in database` If Block... All Good so far"; echo "<br>"; 
            echo "')</script> ";
        $sql = "UPDATE users SET firstname=?, lastname=? address=?, email=?, access_level=?, status=? WHERE id=?";

        if($stmt = mysqli_prepare($link, $sql)){
            echo "<script>alert('";
            echo "Im inside `mysqli_prepare` If Block... All Good so far"; echo "<br>"; 
            echo "')</script> ";
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "sssssii", $param_firstname, $param_lastname, $param_address, $param_email, $param_level, $param_status, $param_id);

            // Set parameters
            $param_firstname = $firstname;
            $param_lastname = $lastname;
            $param_address = $address;
            $param_email = $email;            
            $param_level = $level;
            $param_status = $status;
            $param_id = $id;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Records updated successfully. Redirect to landing page
            echo "<script>alert('";
                echo "Im inside `mysqli_stmt_execute` If Block... All Good so far"; echo "<br>"; 
            echo "')</script> ";
                header("location: index.php");
                exit();
            } else{
            echo "<script>alert('";
                echo "Im inside `mysqli_stmt_execute` If Block... Not Good"; echo "<br>"; 
            echo "')</script> ";
                echo "Something went wrong. Please try again later.";
            }
            // Close statement
            mysqli_stmt_close($stmt);
        }else{
            echo "<script>alert('";
            echo "Im directly into else block from `empty input check If` Block... Not Good"; echo "<br>"; 
            echo "')</script> ";
            echo mysqli_stmt_error($stmt);
        }
    }

    // Close connection
    mysqli_close($link);
} else{
    // Check existence of id parameter before processing further
    if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
        // Get URL parameter
        $id =  trim($_GET["id"]);

        // Prepare a select statement
        $sql = "SELECT * FROM users WHERE id = ?";
        if($stmt = mysqli_prepare($link, $sql)){

            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "i", $param_id);

            // Set parameters
            $param_id = $id;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                $result = mysqli_stmt_get_result($stmt);

                if(mysqli_num_rows($result) == 1){
                    /* Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop */
                    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);

                    // Retrieve individual field value
                    $firstname = $row["firstname"];
                    $lastname = $row["lastname"];
                    $email = $row["email"];
                    $address = $row["address"];
                    $level = $row["access_level"];
                    $status = $row["status"];
                } else{
                    // URL doesn't contain valid id. Redirect to error page
                    header("location: error.php");
                    exit();
                }

            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }

        // Close statement
        mysqli_stmt_close($stmt);

        // Close connection
        mysqli_close($link);
    }  else{
        // URL doesn't contain id parameter. Redirect to error page
        header("location: error.php");
        exit();
    }
}
?>

<?php
// core configuration
include_once "../../config/core.php";

// check if logged in as admin
include_once "../login_checker.php";

// set page title
$page_title = "Update Record";

// include page header HTML
include '../layout_head.php';

echo "<div class='col-md-12'>";

// get parameter values, and to prevent undefined index notice
$action = isset($_GET['action']) ? $_GET['action'] : "";

// tell the user he's already logged in
if ($action == 'already_logged_in') {
    echo "<div class='alert alert-info'>";
    echo "<strong>You</strong> are already logged in.";
    echo "</div>";
} else if ($action == 'logged_in_as_admin') {
    echo "<div class='alert alert-info'>";
    echo "<strong>You</strong> are logged in as admin.";
    echo "</div>";
}

echo "</div>";

//content when logged in
?>
<div class="wrapper" style="width: 500px; margin: 0 auto;">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="page-header">
                    <h2>Update Record</h2>
                </div>
                <p>Please edit the input values and submit to update the record.</p>
                <form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
                    <div class="form-group <?php echo (!empty($firstname_err)) ? 'has-error' : ''; ?>">
                        <label>First Name</label>
                        <input type="text" name="firstname" class="form-control" value="<?php echo $firstname; ?>">
                        <span class="help-block"><?php echo $firstname_err;?></span>
                    </div>
                    <div class="form-group <?php echo (!empty($lastname_err)) ? 'has-error' : ''; ?>">
                        <label>Last Name</label>
                        <input type="text" name="lastname" class="form-control" value="<?php echo $lastname; ?>">
                        <span class="help-block"><?php echo $lastname_err;?></span>
                    </div>
                    <div class="form-group <?php echo (!empty($address_err)) ? 'has-error' : ''; ?>">
                        <label>Email</label>
                        <input type="email" name="email" class="form-control" value="<?php echo $email; ?>" />
                        <span class="help-block"><?php echo $email_err;?></span>
                    </div>
                    <div class="form-group <?php echo (!empty($address_err)) ? 'has-error' : ''; ?>">
                        <label>Address</label>
                        <textarea name="address" class="form-control"><?php echo $address; ?></textarea>
                        <span class="help-block"><?php echo $address_err;?></span>
                    </div>
                    <div class="form-group <?php echo (!empty($level_err)) ? 'has-error' : ''; ?>">
                        <label>Access Level</label>
                        <input type="text" name="level" class="form-control" value="<?php echo $level; ?>">
                        <span class="help-block"><?php echo $level_err;?></span>
                    </div>
                    <div class="form-group <?php echo (!empty($status_err)) ? 'has-error' : ''; ?>">
                        <label>Status</label>
                        <input type="text" name="status" class="form-control" value="<?php echo $status; ?>">
                        <span class="help-block"><?php echo $status_err;?></span>
                    </div>
                    <input type="hidden" name="id" value="<?php echo $id; ?>"/>
                    <input type="submit" class="btn btn-primary" value="Submit">
                    <a href="index.php" class="btn btn-default">Cancel</a>
                </form>
            </div>
        </div>
    </div>
</div>
</body>
</html>

I updated the code please run that code. I cannot guess more what else could be be wrong but i have added some echo to your code. please run it and find where is the error. Double check your bind_parameter type.they must be exactly same as your database table types. i only help you as giving u an example not the whole solution.

Now you can see the alert showing where are you so you can track down the problem

Hope it will help and solve your problem.

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