我的目标是能够根据用户可以选择的ID提取特定数据。最初,我会使用以下内容显示可用的ID:
<form action = "admin.php" method = "POST">
<?php
$sql = "SELECT id FROM mensproducts";
$result = mysqli_query($connection,$sql);
if(mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
echo $id;
?>
<input type ="submit" name = "submitid" value = "Choose Id"/> <?php
}
}
这似乎很好用,因为显示的可用ID旁边有一个按钮,该按钮应该允许用户从所选ID中提取数据。 我提取该数据的代码是:
if (isset($_POST['submitid'])) {
$result = mysqli_query($connection,"SELECT * FROM mensproducts WHERE id =
'$id'");
while($row = mysqli_fetch_assoc($result)){
echo "
<div class = 'id'> Id = ".$row['id']."</div>
<div class='name'>".$row['name']."</div>
<div class='desc'>".$row['description']."</div>
<div class='price'>£".$row['price']."</div>
</form>
</div>";
}
}
?>
</select>
</form>
但是,无论我按什么按钮,似乎只显示第三列的数据。我的SQL语句有问题吗?格式化?
答案 0 :(得分:1)
假设您发布的按钮列表和表单处理代码块都位于同一文件admin.php
中,我相信它总是在表中显示第3行(最后一行),因为第一个提取{{1 }}循环定义变量while
,然后在以后处理表单时直接使用它。
相反,要选择一个$id
值并将其传递给表单处理代码,您将需要一个附加的$id
标记来保存其值,并从<input>
中检索它。表格处理:
$_POST
然后在表单处理器中,检索表单现在发送的<?php
$sql = "SELECT id FROM mensproducts";
$result = mysqli_query($connection,$sql);
if(mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
// THIS final value of $id is what is mistakenly being passed to your SQL, whatever it holds at the end of the loop.
$id = $row['id'];
echo $id;
// Create an <input> with the $id -- this uses a hidden one
// Note: each listing is now its own separate <form>
// This does not matter for the HTML, though it might require changes to your CSS if it causes different visual appearance.
// Necessary so that the same input name can be used.
?>
<form action="admin.php" method="POST">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="submit" name="submitid" value="Choose Id"/>
</form>
,并在SQL中使用它。
$_POST['id']
注意:我要在此处添加if (isset($_POST['submitid'])) {
// Get your $id from the form post
$id =mysqli_real_escape_string($connection, $_POST["id"]);
$result = mysqli_query($connection,"SELECT * FROM mensproducts WHERE id = '$id'");
while($row = mysqli_fetch_assoc($result)){
echo "
<div class='id'> Id = ".$row['id']."</div>
<div class='name'>".htmlspecialchars($row['name'])."</div>
<div class='desc'>".htmlspecialchars($row['description'])."</div>
<div class='price'>£".htmlspecialchars($row['price'])."</div>
</div>";
}
}
?>
// I closed the </form> tag earlier.
,这是您必须执行的最低限度的工作,以保护您的代码免遭SQL注入造成的数据库篡改。更好的方法是在MySQLi中使用mysqli_real_escape_string()
。有关详细信息和示例,请参见How can I prevent SQL injection in PHP。
注2:我删除了html属性周围的多余空格,将prepare()/bind_param()/execue()
变成了<input name = 'submitid'>
。尽管当今大多数浏览器都不会在意,但公认的惯例是不要在属性中<input name='submitid'>
周围放置空格
注3:我added htmlspecialchars()
围绕打印到HTML中的数据库值。这样可以正确编码任何可能破坏标记的字符,例如=
。要养成重要的习惯。