更新MySQL PHP上的行

布扎伊德

我想更新表上的一行,但未更新。这是我的html和php代码:

<?php
if ($_GET) {
    if (isset($_GET['id'])) {
        $id = preg_replace('#[^0-9]#', '', $_GET['id']);
        echo $id;
        $query = "SELECT * FROM posts WHERE id='{$id}'";
        $result = mysqli_query($connect, $query);
        $rows = mysqli_fetch_assoc($result);
    } elseif (empty($_GET['id'])) {
        header("location: manage_posts.php");
    }
}
?>
<form action="modify_post.php?id=<?php echo $id; ?>" method="post">
    <h3>Post Title <?php //echo $id; ?></h3>
    <input name="title" value="<?php echo $rows['title'];?>" type="text" placeholder="Title here ..." id="title" required>
    <h3>Post Content</h3>
    <textarea name="content" required  placeholder="Title here ..." style="resize: none"><?php echo $rows['content'];?></textarea>
    <br/>
    <input type="submit" value="Update" id="submit"/>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ($_POST['title'] != "" || $_POST['content'] != "") {
        $id = preg_replace('#[^0-9]#', '', $_GET['id']);
        $sql = "UPDATE posts SET title='{$_POST['title']}', content='{$_POST['content']}' WHERE id='{$id}'";
        $update_result = mysqli_query($connect, $sql);

        if (isset($result)) {
            echo "<h2>Update successfully, redirecting back ...</h2>";
        } else {
            echo "Record hasn't been Updated" . mysqli_errno($result);
        }

        header("location: manage_posts.php");
    } else {
        echo "<h3>Please fill all fields</h3>";
    }
}
?>

这就是我能想到的一切!

我不知道问题出在哪里?

沃尔克

a)避免进行SQL注入,例如使用准备好的语句+参数
b)添加更多的错误处理和参数检查。

<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo 'wrong method';
}
else if ( !isset($_POST['title'], $_POST['content']) ) {
    echo 'missing POST parameters';
}
else if ( !isset($_GET['id']) ) {
    echo 'missing GET parameter';
}
else if ($_POST['title'] == "" || $_POST['content'] == "") {
    echo '<h3>Please fill all fields</h3>';
}
else {
    $stmt = $connect->prepare('UPDATE posts SET title=?, content=? WHERE id=?');
    if ( !$stmt ) {
        trigger_error('prepare failed', E_USER_ERROR);
    }
    else  if ( !$stmt->bind_param('sss', $_POST['title'], $_POST['content'], $_GET['id']) ) {
        trigger_error('bind_param failed', E_USER_ERROR);
    }
    else if ( !$stmt->execute() ) {
        trigger_error('execute failed', E_USER_ERROR);
    }
    else {  
        echo '# of updated rows: ', $stmt->affected_rows();
    }
}

也可以看看

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章