[英]PHP MYSQL updating multiple rows using values from an array
我已經在這個問題上解決了一段時間,並且已經停留了幾天。 我所擁有的是一個基本的博客系統,現在我只能嘗試從列表中刪除/隱藏帖子。
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
Commands out of sync; you can't run this command now
我想我需要使用mutli_query
或$stmt->store_result()
但這是我第一次使用php和mysql,我不知道該如何處理。
好了,我找到了另一種解決方法,我所做的就是將查詢隱藏起來,將查詢隱藏到運行實際獲取信息的while()
下面。 我希望我早點意識到這一點。
使用此代碼
$checked = array ( 0 => 10, 1 => 8, 2 => 4 );
//print_r($checked);
$hide_post = 'UPDATE post SET hide_post=1
WHERE post_id IN (' . implode(',', array_map('intval', $checked)) . ')';
echo $hide_post;
您的查詢成為
UPDATE post SET hide_post=1 WHERE post_id IN (10,8,4)
在phpmyadmin
運行相同的查詢,並檢查相同的查詢是否返回ant錯誤。
事實證明,我的問題不是由查詢本身引起的,而是我放置它的位置。
為避免該錯誤,我所要做的就是: Commands out of sync; you can't run this command now
Commands out of sync; you can't run this command now
是執行第二個查詢以隱藏/刪除用戶選擇的帖子,並將查詢放在while()
循環之后,該循環將fetch()
每個帖子。
基本上,我試圖在第一個查詢完成之前進行第二個查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.