使用 PHP 从 MySQL 数据库表中删除多行时,使用复选框选择链接需要仔细编码确保成功执行。此代码片段提供了常见问题的解决方案:
<code class="php"><html> <head> <title>Links Page</title> </head> <body> <h2>Choose and delete selected links.</h2> <?php $dbc = mysqli_connect('localhost','root','admin','sample') or die('Error connecting to MySQL server'); $query = "select * from links ORDER BY link_id"; $result = mysqli_query($dbc,$query) or die('Error querying database'); $count=mysqli_num_rows($result); ?> <table width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <td> <form name="form1" method="post" action=""> <table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC"> <tr> <td bgcolor="#FFFFFF"> </td> <td colspan="3" bgcolor="#FFFFFF"> <strong>Delete multiple links</strong> </td> </tr> <tr> <td align="center" bgcolor="#FFFFFF">#</td> <td align="center" bgcolor="#FFFFFF"> <strong>Link ID</strong> </td> <td align="center" bgcolor="#FFFFFF"> <strong>Link Name</strong> </td> <td align="center" bgcolor="#FFFFFF"> <strong>Link URL</strong> </td> </tr> <?php while ($row=mysqli_fetch_array($result)) { ?> <tr> <td align="center" bgcolor="#FFFFFF"> <input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>"> </td> <td bgcolor="#FFFFFF"> <?php echo $row['link_id']; ?> </td> <td bgcolor="#FFFFFF"> <?php echo $row['link_name']; ?> </td> <td bgcolor="#FFFFFF"> <?php echo $row['link_url']; ?> </td> </tr> <?php } ?> <tr> <td colspan="4" align="center" bgcolor="#FFFFFF"> <input name="delete" type="submit" value="Delete"> </td> </tr> </table> </form> </td> </tr> </table> <?php // Check if delete button active, start this if(isset($_POST['delete'])) { $checkbox = $_POST['checkbox']; for($i=0; $i<count($checkbox); $i++) { $del_id = $checkbox[$i]; $sql = "DELETE FROM links WHERE link_id='$del_id'"; $result = mysqli_query($dbc, $sql); // Pass the database connection here } // if successful redirect to view_links.php if($result){ echo '<meta http-equiv="refresh" content="0;URL=view_links.php">'; } } mysqli_close($dbc); ?> </body> </html></code>
修复:
通过这些修改,代码应该根据所选的复选框正确删除多行。
以上是如何在 PHP 中使用复选框删除多行:解决常见错误并确保成功执行?的详细内容。更多信息请关注PHP中文网其他相关文章!