php - 如何获取表中特定记录的ID - PHP
问题描述
我正在尝试使用切换开关更改 MySQL 文章表中 is_public 列的值。如果我将输入(切换)包装在内部以使用 $_GET 方法在articles.php中进行必要的更改来获取记录的ID,那么它不会将is_public的数据获取到切换中。有没有其他方法可以获取特定记录的 id?
这是 all-articles.php 代码:
<table id="datatable" class="table table-hover" style="width:100%">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Author</th>
<th>Abstract</th>
<th>category</th>
<th>Date</th>
<th>Action</th>
<th>Publish</th>
</tr>
</thead>
<tbody>
<?php foreach($articles as $key => $article): ?>
<tr>
<td><?php echo $key+1 ?></td>
<td><?php echo $article['title'] ?></td>
<td><?php echo $article['author_id'] ?></td>
<td><?php echo $article['abstract'] ?></td>
<td><?php echo $article['category_id'] ?></td>
<td><?php echo $article['entry_date'] ?></td>
<td>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-primary btn-sm">Edit</button>
<button type="button" class="btn btn-success btn-sm">Show</button>
<button type="button" class="btn btn-danger btn-sm">Delete</button>
</div>
</td>
<td>
<form action="all-articles.php" method="post">
<label class="custom-toggle">
<?php if($article['is_public']): ?>
<input type="checkbox" checked name="check">
<?php else: ?>
<input type="checkbox" name="uncheck">
<?php endif; ?>
<span class="custom-toggle-slider rounded-circle"></span>
</label>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
解决方案
好吧,您可以在表单中发送文章 ID,然后收听它并用它做您想做的事情。所以,
// As you are already in foreach loop so,
<form action="all-articles.php" method="post">
<label class="custom-toggle">
<?php if($article['is_public']): ?>
<input type="checkbox" checked name="published" value="<?php echo $article['id']; ?>>
<?php else: ?>
<input type="checkbox" name="published" value="<?php echo $article['id']; ?>>
<?php endif; ?>
<span class="custom-toggle-slider rounded-circle"></span>
</label>
</form>
然后在你/all-articles.php
检查$_POST['check']
which 应该给article id
. 使用该 ID 查询您的数据库并切换is_public
列
另一种方法是发送一个隐藏字段,例如
// As you are already in foreach loop so,
<form action="all-articles.php" method="post">
<label class="custom-toggle">
<?php if($article['is_public']): ?>
<input type="checkbox" checked name="published" value="<?php echo $article['id']; ?>>
<input type="hidden" name="is_published" value="yes"> or 1
<?php else: ?>
<input type="hidden" name="is_published" value="no"> or 0
<input type="checkbox" name="published" value="<?php echo $article['id']; ?>>
<?php endif; ?>
<span class="custom-toggle-slider rounded-circle"></span>
</label>
</form>
推荐阅读
- foreign-keys - 在外键关系上显示名称属性
- git - 当 Git Merge Vs Git Override 发生时,同时使用同一个文件
- powershell - 是否可以从另一份工作开始工作?
- listview - 适用于 iOS 的 Xamarin.Forms ListView ItemTapped 背景
- python - 如何使用beautifulsoup在python中按类查找html标签
- azure - 部署 VMSS 并注入机密
- android - ic_launcher 图像未显示
- c# - 线程安全窗口定位
- python - Netaddr 返回 NameError 而不是 ImportError
- django - 如何面对无效过滤器:自定义 django 模板标签中的“has_group”错误