如何在PHP中更新记录,sqli

时间:2017-04-19 12:04:03

标签: php html mysql sql

我想在数据库中更新我的记录并在表格中显示但是这段代码我无法理解发生了什么问题。请通知我谢谢。亲爱的,我非常感谢你。我怎么能纠正它?如何可能以及此代码中出现的问题

<?php
include("connection.php");

$edit_rec = $_GET['edit'];

$query= "SELECT * from card_rec where id='$edit_rec'";

$run = mysqli_query($con,$query);
$row = mysqli_fetch_row($run);

if ($_POST) 
{
    $name = $_POST['name'];
    $fname = $_POST['fname'];
    $school = $_POST['school'];
    $address = $_POST['address'];
    $contact = $_POST['contact'];
    $id = $_POST['id'];

    $query1="UPDATE card_rec SET name='$name', fname='$fname', school='$school',address='$address',contact= '$contact' WHERE id='$id'";

    if ($query1) {
        echo "<script>alert('Record Update'); window.location = 'card_rec.php' </script>";
    }
    else
    {
        echo "not update";
    }
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Update</title>
</head>
<body>

<form method="post">
    <input type="hidden" name="id" value="<?php echo $row[0] ?>"><br>
<input type="text" name="name" value="<?php echo $row[1] ?>"><br>
<input type="text" name="fname" value="<?php echo $row[2]  ?>"><br>
<input type="text" name="school" value="<?php echo $row[3]  ?>"><br>
<input type="text" name="address" value="<?php echo $row[4]  ?>"><br>
<input type="text" name="contact" value="<?php echo $row[5] ?>"><br>
<input type="submit" name=" submit">
</form>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

使用mysqli_error()函数获取最近函数调用的错误描述。

$query= "SELECT * from card_rec where id='$edit_rec'";
$run = mysqli_query($con,$query) or die (mysqli_error($con));



$query1="UPDATE card_rec SET name='$name', fname='$fname', school='$school',address='$address',contact= '$contact' WHERE id='$id'";

if (mysqli_query($con, $query1)) {
    echo "updated";
} else {
    echo "not updated";
}

答案 1 :(得分:0)

肯定你没有运行最后一个查询所以它没有做任何事情。你的代码需要一些优化。

总是检查$ _POST操作而不是空,并尝试使用类而不是这个混乱的代码。

   <?php

$serverName = "localhost";
$username = "username";
$password = "password";
$dbName = "myDB";

// Create connection
$conn = new mysqli($serverName, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if (isset($_POST) and !empty($_POST)) {

$name = $_POST['name'];
$fname = $_POST['fname'];
$school = $_POST['school'];
$address = $_POST['address'];
$contact = $_POST['contact'];
$id = $_POST['id'];

$query1="UPDATE card_rec 
         SET 
         name='$name', 
          fname='$fname', 
           school='$school', 
           address='$address', 
           contact= '$contact' 
            WHERE id='$id'";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
 echo "Error updating record: " . $conn->error;
}

}