如何呼应提交输入表单与特定ID的名称
我当前的代码,这不符合我的需求,看起来像以下:如何呼应提交输入表单与特定ID的名称
<?php
$con = mysqli_connect("localhost", "root", "", "blogs");
$sql = "SELECT * FROM foods order by date desc";
$result = mysqli_query($con, $sql);
while ($r = mysqli_fetch_array($result)) {
//my variables
$buttonname = $r['id']; //for name I want to set on submit input on every echo of form of each results. Ps. My id on my database are set to auto increment.
$lhtitle = $r['title'];
$lhcategory = "foods";
$lhimage = $r['image'];
$lhtext = $r['text'];
echo "<div class='content-content'>";
echo strtoupper("<div class='L-TITLE'>$lhtitle</div>");
echo "<form action='' method='POST'><input type ='submit' value='Add to Collection' name = '$buttonname'";
echo "class='addto-button'></form>";
echo "<div class='content-img'>";
echo "<img style = 'width:100%;' src='images/$lhimage' alt='no image inserted'>";
echo "</div>";
echo "<div class='content-description'><p>$lhtext</p></div>";
echo "</div>";
}
if (isset($_POST[$buttonname])) {
$usn = $_SESSION['logged'];
$sql = "INSERT INTO `$displayuserid` (title,category,image,text) SELECT '$lhtitle','$lhcategory','$lhimage','$lhtext' FROM foods WHERE id = '$buttonname'";
mysqli_query($con , $sql);
}
?>
当我运行这段代码,只有第一个ID是1
$ buttonname读取。但我需要所有ID。
你编写PHP变量作为HTML代码
变化
echo strtoupper("<div class='L-TITLE'>$lhtitle</div>");
echo "<img style = 'width:100%;' src='images/$lhimage' alt='no image inserted'>";
echo "<form action='' method='POST'><input type ='submit' value='Add to Collection' name = '$buttonname'";
要
echo strtoupper("<div class='L-TITLE'>".$lhtitle."</div>");
echo "<img style = 'width:100%;' src='images/".$lhimage."' alt='no image inserted'>";
echo "<form action='' method='POST'><input type ='submit' value='Add to Collection' name = '".$buttonname."'";
谢谢。但我的主要问题仍然是一个问题。如果(isset($ _POST [$ buttonname]))它仍然只读第一个ID是'1' –
不是真的知道你的意思是 “只有第一个ID是 '1' $ BUTTONNAME读”但也许问题可能在这里:
你是第一次循环所有的结果,每次你加载页面。因此,当你的结果是2个记录,例如id和1,输入的值将是name ='1'和name ='2',但变量$buttonname
将在每个循环后为2页面加载。
然后$_POST[$buttonname]
将变成$_POST["2"]
,这将是casted to an integer像$_POST[2]
。
所以,如果你有这样的检查:
`if (isset($_POST[$buttonname])) {`
这将改为
`if (isset($_POST[2])) {`
当你点击第一个按钮,该$_POST
看起来像:
Array
(
[1] => Add to Collection
)
而且第二个按钮:
Array
(
[2] => Add to Collection
)
所以你可以看到,如果语句只会匹配最后输入元件和第一会导致:
注意:未定义抵消:2
希望这有助于你解决你的问题。
你明白了我的观点,但对不起,我没有得到你的答案T_T请你详细说明一下我应该怎么做? :( –
我认为你想用'$ buttonname'作为id来插入数据到你的数据库中,你需要的id在'name'属性中(name =“1”等),这将成为'$ _POST' arrray。一个可能性是使用[array_search](http://php.net/manual/en/function.array-search.php)通过搜索值“Add to Collection “like $ inputName = array_search(”Add to Collection“,$ _POST); if(false!== $ inputName){}'你也应该考虑在sql中如何使用它们sql注入。 –
信息不足!更新与完整信息 –