0

I am just trying to access following code but unfortunately, I couldn't run this script successfully. always got an error not updated. in my db i have only 3 field id, lname, fname here is following my code.

index.php

<div class="left-box">
            <h3>UPDATE</h3>
            <form action="update.php" method="post">
            <select name="choice">
                    <option value = "action">Update First or Last Name</option>
                    <option value = "fname">First Name</option>
                    <option value = "lname">Last Name</option>
            </select>
                <input type="text" name="id" placeholder="Choose ID"><br>
                <input type="text" name="new_value" placeholder="New Value"><br>
                <button type="submit" name="submit" value="send">UPDATE</button>
            </form>
        </div>

update.php

<?php
if(isset($_POST["submit"])){
    $choice = $_POST["choice"];
    $id = $_POST["id"];
    $new_value = $_POST["new_value"];
    if($id != "" AND $new_value != "" AND $choice != "")
    {
        require('db.php');
        $db_connection = connect_db();

        $status = update_data($db_connection,$id,$choice,$new_value);
        if($status) {
            header("Location: index.php?id=success&v=Updated succesfully");
        }
        header("Location: index.php?id=error&v=Not Updated");
    }
    else {
        //echo '<script type="text/javascript">alert("hi")</script>';
        header("Location: index.php?id=error&v=Error: All Fields Required");
    }
}
else {
    header("Location:index.php");
} ?>

db.php

   function connect_db() {
$con = mysqli_connect("localhost","root","","test");
if(!$con){
    die("database connection not established");
}
return $con; }

function update_data($con,$id,$choice,$new_value){  
$sql="";

if($choice == "fname") {
            $sql = "UPDATE crud SET fname = '$new_value' WHERE id = '$id' ";
        }
        else{
            $sql = "UPDATE crud SET lname = '$new_value' WHERE id = '$id' ";
        }
        $result = mysqli_query($con, $sql);

        if(mysqli_affected_rows($con))
        {
            return true;
        }
        return false;
}
nady gold
  • 109
  • 10

1 Answers1

0

Try below query.

$sql = "UPDATE crud SET fname = '".$new_value."' WHERE id = $id";
$sql = "UPDATE crud SET lname = '".$new_value."' WHERE id = $id";
Harsh Barach
  • 947
  • 9
  • 18