【问题标题】:Add link to echo'd HTML from SQL data从 SQL 数据中添加指向回显 HTML 的链接
【发布时间】:2013-08-09 11:42:16
【问题描述】:

回到另一个简短的问题。我在下面有这段代码,它从数据库中回显了产品名称。我想要做的是将回显的产品名称作为指向另一个名为 product.php 的页面的链接,每个链接都需要有一个唯一的 ID,例如

<a href="product.php?id=1">Product Name</a> 

我该怎么做呢?非常感谢。我会指出我对 PHP 很陌生。

<?php
//create an ADO connection and open the database
$conn = new COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\WebData\Northwind.mdb");

//execute an SQL statement and return a recordset
$rs = $conn->execute("SELECT product_name FROM Products");
$num_columns = $rs->Fields->Count();

echo "<table border='1'>"; 
echo "<tr><th>Name</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
     echo "<tr>";
     for ($i=0; $i <  $num_columns; $i++) {
         echo "<td>" . $rs->Fields($i)->value . "</td>";
     }
     echo "</tr>";
     $rs->MoveNext();
}
echo "</table>";

//close the recordset and the database connection
$rs->close();
$rs = null;
$conn->close();
$conn = null;
?>

【问题讨论】:

  • 您的 Products 表是否有唯一的 ID 字段?
  • 抱歉,请查看更新后的问题。
  • 我打算使用 产品名称 来识别他们
  • 在下面发布了答案,只需确保您首先在产品数据库中有一个唯一的 ID 字段。

标签: php sql hyperlink


【解决方案1】:

假设您的 Products 表有一个名为“id”的唯一 ID 字段,请将您的选择更改为:

$rs = $conn->execute("SELECT id, product_name FROM Products");

当您要创建链接时,请使用该字段并将其传递到 URL。所以你会有product.php?id=&lt;?= $thatIdField; ?&gt;

示例代码:

echo "<table border='1'>"; 
echo "<tr><th>Name</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
     echo "<tr>";
     for ($i=0; $i <  $num_columns; $i++) {
         echo "<td><a href=\"product.php?id=" . $rs->Fields('id').value . "\">" . $rs->Fields($i)->value . "</a></td>";
     }
     echo "</tr>";
     $rs->MoveNext();
}
echo "</table>";

【讨论】:

  • 现在我提出了一个完全愚蠢的问题。我如何使用上面的代码使该产品成为链接?想不出语法。谢谢。
  • 在上面的代码中,您正在遍历记录上的所有字段,这是通用的。您需要指向特定的 ID 字段。我不熟悉 ADODB 的 Field() 语法,但你可以试试,在循环之外:
  • $rs-&gt;Fields('id');(假设该字段为 id)
  • echo "
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 2015-01-17
相关资源
最近更新 更多