无法更新mysqli中的记录

时间:2017-02-08 07:06:26

标签: php mysql mysqli sql-update

我只是想尝试访问以下代码,但不幸的是,我无法成功运行此脚本。总是得到错误没有更新。在我的数据库中,我只有3个字段ID,lname,fname 这是遵循我的代码。

的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;
}

1 个答案:

答案 0 :(得分:-1)

尝试以下查询。

$sql = "UPDATE crud SET fname = '".$new_value."' WHERE id = $id";
$sql = "UPDATE crud SET lname = '".$new_value."' WHERE id = $id";