【发布时间】:2013-03-08 22:41:48
【问题描述】:
我已经解决这个问题一段时间了,我已经被困了几天。 我拥有的是一个基本的博客系统,现在我一直在尝试从列表中删除/隐藏帖子。
if(isset($_POST['hideBtn']) && isset($_POST['hidePost'])){
$checked = $_POST['hidePost'];
print_r($checked);
} elseif(isset($_POST['hideBtn']) && !isset($_POST['hidePost'])){
echo "Nothing Selected";
}
列表中显示的每个帖子都有一个复选框。
<input type="checkbox" name="hidePost[]" value="<?php echo $post_id;?>">
现在,当我运行上述脚本并检查帖子 10、8 和 4 并按下“hideBtn”按钮时,我得到:
数组([0] => 10 [1] => 8 [1] => 4)
这就是我卡住的地方。我正在尝试获取该数组的值并在 MSQL 查询中使用它们来查找我想要隐藏的 post_id:
if(isset($_POST['hideBtn']) && isset($_POST['hidePost'])){
$checked = $_POST['hidePost'];
print_r($checked);
$hide_post = 'UPDATE post SET hide_post=1
WHERE post_id IN (' . implode(',', array_map('intval', $checked)) . ')';
$db->query($hide_post);
} elseif(isset($_POST['hideBtn']) && !isset($_POST['hidePost'])){
echo "Nothing Selected";
}
这给了我和以前一样的结果:
数组([0] => 10 [1] => 8 [1] => 4)
并且数据库中没有任何变化。
这里是数据库表,hide_post 默认为0:
发布
post_id user_id 标题正文 hide_post
编辑
好吧,看来我的问题是由于一个连接上的数据库查询过多。
这是我在页面顶部包含的内容:
<?php
//get record count
$record_count = $db->query("SELECT * FROM post");
//number of posts per page
$per_page = 4;
//number of pages
$pages = ceil($record_count->num_rows/$per_page);
//get page number
if(isset($_GET['p']) && is_numeric($_GET['p'])){
$page = $_GET['p'];
}else{
$page = 1;
}
if($page<=0){
$start = 0;
}else{
$start = $page * $per_page - $per_page;
}
$prev = $page - 1;
$next = $page + 1;
//get post information from database
$query = $db->prepare("SELECT post_id, title, LEFT(body, 100) AS body, posted, category, user_name FROM post
INNER JOIN categories ON categories.category_id=post.category_id
INNER JOIN user ON user.user_id=post.user_id
WHERE hide_post = 0
order by post_id desc limit $start, $per_page");
$query->execute();
$query->bind_result($post_id, $title, $body, $posted, $category, $user_name);
?>
根据我所读到的关于我遇到的错误:Commands out of sync; you can't run this command now 我想我需要使用mutli_query 或$stmt->store_result(),但这是我第一次使用 php 和 mysql,我不知道该怎么做关于它。
编辑 2
好吧,我找到了另一种解决方法,我所做的只是将隐藏帖子的查询移动到运行实际获取帖子信息的while() 下方。我希望我能早点意识到这一点,呵呵。
【问题讨论】:
-
能否打印
$hide_post看看内爆是否正确完成? -
确保为 SQL 查询启用错误报告(使用
mysql_error()或mysqli_error($link),表名/顺序可能不正确。 -
内爆看起来找到了我,我检查了帖子 9 和 7,它给了我:
UPDATE post SET hide_post=1 WHERE post_id IN (9,7) -
@Titanium 好的,所以当我运行
$db->query($hide_post) or die('Could not connect: ' . mysqli_error($db));时,我会在空白页上看到这个:Could not connect: Commands out of sync; you can't run this command now -
@Brian - 很高兴你修复了它。如果您自己解决它,最好创建自己的答案并勾选它 - 这样它会从未回答的列表中删除问题,因此数据 API 可以正确地将“问题”与“答案”分开。如果你得到一个 mo,你可以使用 Rollback 来解决这个问题 - 谢谢。
标签: php mysql arrays mysqli sql-update