在mysql php上更新行
我想更新表上的一行,但它没有更新。 这是我的html和php代码:在mysql php上更新行,php,mysql,Php,Mysql,我想更新表上的一行,但它没有更新。 这是我的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($
<?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)避免,例如使用+参数
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();
}
}
有错误消息吗?标题或内容是否包含引号?您可以接受sql注入<代码>$update\u result=mysqli\u。。。if(isset($result))
-什么是$result?和$\u GET['id']
是否正确?还有if($\u GET){
如果在下面检查是否设置了id
,似乎是多余的。你能描述一下当前的行为吗?你是否成功地得到了更新,并重定向回了。
而它只是没有在数据库中更新?你的标题不起作用,因为你在它前面输出内容。我认为这是面向对象的!是的,它是!那又怎样?我对这门语言还是个新手,只是应用了我在php程序中所学的知识mysqli\u prepare($connect,…)
vs$connect->prepare()
-没什么大不了的。顺便说一句:我没有考虑到打印表单代码和处理响应是在同一个脚本中进行的,因此您可能必须调整第一个if条件。