我目前正在使用复选框填充数组,将数组变量内爆并在 DELETE 函数的 IN 子句中使用该变量。var_dump 显示我正在创建一个正确的查询,但我无法进行任何删除。这是解决我一个月左右的现有问题的一种新方法。
这就是我所拥有的。
//Connect to the db
$id_array = NULL;
// Make the query to display user's uploads
$q = "SELECT upload_id, title, genre, length, created, views
FROM upload
WHERE owner_id =". $_SESSION['user_id'] ."
ORDER BY title ASC";
$r = mysqli_query ($dbc, $q); // Run the query
if($r)
{
// If it ran okay, display the records
echo '<table align="center"
cellspacing="3" cellpadding="3"
width="75%">
<tr><td align="left"><b>Title</b></td>
<td align="left"><b>Genre</b></td>
<td align="left"><b>Pages</b></td>
<td align="left"><b>Submitted</b></td>
<td align="left"><b>Views</b></td>
</tr>';
// Fetch and print all the records:
?><form action="/nbproject/newwriter_profile.php" method="post">
<?php
while ($row = mysqli_fetch_array($r,MYSQLI_ASSOC))
{
echo '<tr><td align="left">' .
$row['title'] . '</td><td align="left">'
. $row['genre'] . '</td><td align="left">'
. $row['length'] . '</td><td align="left">'
. $row['created'] . '</td><td align="left">'
. $row['views'] . '</td><td align="left">' //. var_dump($row) //dump row value for testing
. '<input type="checkbox" name="checkbox[]" value= "'.$row['upload_id'].'"'.' />'.' </td>'. '</tr>';
}
echo '</table>'; // Close the table
?>
上面的代码创建了一个简单的表格,每条记录都有一个对应的复选框,勾选删除然后点击“删除”
<input type="submit" name="delete" value="Delete" align="right"/>
</form>
<?php
} // End of if ($r) IF.
mysqli_close($dbc); // Close the database connection
自定义删除功能:
function submit_delete() {
if(!is_null($_POST['delete']) && !is_null($_POST['checkbox'])) { //Check to see if a delete command has been submitted.
//This will dump your checkbox array to your screen if the submit works.
//You can manually check to see if you're getting the correct array with values
// var_dump($_POST['checkbox']);//Comment this out once it's working.
$id_array = $_POST['checkbox'];
$id_array = array_map('intval', $id_array);
$id_array = array_unique($id_array);
$id_array = implode(',',$id_array);
//var_dump($id_array);
deleteUploads($id_array);
}
else {
echo "Error: submit_delete called without valid checkbox delete.";//var_dump($_POST['checkbox']);
}
}
$delete_success = false;
function deleteUploads ($id_array) {
require_once(my connection to db);
mysqli_free_result($r);
if (count($id_array) <= 0) { echo "Error: No deletes in id_array!"; echo 'wtf'; }
//var_dump($id_array);
上面的 var dump 显示正确的 id,如我的 mysql 数据库中所示
$gone = "DELETE FROM `upload` WHERE `upload_id` IN ("."$id_array".")";
var_dump($gone);
上面的 var 验证查询格式是否正确,用逗号分隔 id
$goodbye = mysqli_query($dbc, $gone);
if ($goodbye) { $delete_success = true; var_dump($delete_success);}
else { $delete_success = false;}
var_dump($delete_success);
上面的 var dump 显示 bool false
//mysqli_close($dbc);
if($delete_success == true) { echo 'done';
header('Location: newwriter_profile.php');
} else
{
echo "Error b/c delete failed";
在检查任意数量的框并点击删除后显示上面的回声
}
}
submit_delete();
mysqli_free_result($goodbye);
mysqli_close($dbc);
?>