如何回显具有特定ID

时间:2017-11-25 10:48:57

标签: php mysqli

我目前的代码不能满足我的需求,如下所示:

<?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);
}
?>

当我运行此代码时,只有1 $ buttonname的第一个ID读取。但我需要所有身份证。

2 个答案:

答案 0 :(得分:0)

您将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."'";

答案 1 :(得分:0)

不确定你的意思是“只有'1'$ buttonname的第一个ID读取”但可能问题可能在这里:

每次加载页面时,您首先循环所有结果。

因此,如果结果是2条记录,例如ids 1和2,则输入的值将是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
)

正如您所看到的,if语句只匹配最后一个输入元素,第一个输出元素将导致:

  

注意:未定义的偏移量:2

希望这可以帮助您解决问题。