连接基于 sql id 的整数,以便在 html ID 标记中使用


Concatenating an integer based on an sql id for use in a html ID tag

我目前正在建立一个网站作为我课程的一部分。该网站是一个电子商务网站。我将产品存储在SQL数据库中,然后使用php脚本将每一行回显到表中。我已经设法做到这一点,但是,我现在希望在每个产品上添加一个按钮,该按钮将包含一个 href,可将所选产品添加到购物车中。唯一的问题是,要构建购物车数组,我需要 ID,要在循环中设置 ID,您必须连接一个整数,我不知道如何在我的脚本中执行此操作,这是我目前拥有的,任何帮助将不胜感激。

    while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td><br>".$row['Name']."</td><br>";
echo "<br>";
echo "<td><img src=".$row['Image']."height='200' width = '200'"."</td><br>";
echo "<br>";
echo "<td>Price: £".$row['Price']."</td><br>";
echo "<button type='button'><a href='test.php' id=>Buy</a></button>";
echo "</tr>";

}

提前感谢,我希望我已经提供了足够的细节。

有几种方法可以做到这一点。

$id = 123; // as an example. Use the appropriate variable for this.
echo "<button type='button'><a href='test.php' id=$id>Buy</a></button>";
echo "<br>";
echo "<button type='button'><a href='test.php' id='"$id'">Buy</a></button>";

在HTML源代码中揭示

<button type='button'><a href='test.php' id=123>Buy</a></button><br><button type='button'>
<a href='test.php' id="123">Buy</a></button>

取决于你是否希望引用它们,如果这就是问题所在。

或:

echo "<button type='button'><a href='test.php' id='".$id."'>Buy</a></button>";

与 HTML 源代码显示:

<button type='button'><a href='test.php' id='123'>Buy</a></button>

然后,您可以使用GET数组拉取数据。

即:

$var = $_GET['id'];

然后:

echo "<button type='button'><a href='test.php?id=".$id."'>Buy</a></button>";

网页来源:

<button type='button'><a href='test.php?id=123'>Buy</a></button>

while循环中,您可以为 id 分配一个变量。

即:

$id = $row['id'];

我必须注意,如果您的数据包含单引号,使用单引号可能会产生不利影响,因此最好使用双引号。

即:(和转义双引号)

echo "<button type='"button'"><a href='"test.php?id=".$id."'">Buy</a></button>";

在 HTML 源代码中生成此内容:

<button type="button"><a href="test.php?id=123">Buy</a></button>

实际上,上周我对此有第一手经验,HTML 源代码揭示了有关格式错误的 HTML 标记的警告,其中包含 Mark's Bar & Grill 等数据。


while ($row = mysqli_fetch_assoc($result)){
    $id = $row['id']; // assuming you have a row for id.
    // all your other code
    echo "<button type='button'><a href='test.php?id=".$id."'>Buy</a></button>";
}

例如:

$name = "Bob's Bar & Grill";
echo "<button type='button'><a href='test.php' name='".$name."'>Buy</a></button>";

将在 HTML 源代码中生成No space between attributes警告。

从 HTML 源代码:

<button type='button'><a href='test.php' name='Bob's Bar & Grill'>Buy</a></button>

如果与 CSS 规则一起使用,可能会产生不利影响。


这将与您名称$row['Name']等的其他行有关。

  • 小心点。

不要担心它是一个整数。只需使用从数据库重新调整的值,就像对字符串所做的那样。它将从 int 转换为字符串。另请注意,您为创建字符串而执行的串联并不是真正需要的。由于 php 变量以 $ 开头,因此您可以像这样内联编写它们:

echo "<button type='button'><a href='"test.php'" id='"$row['id']'">Buy</a></button>";