简体   繁体   English

PHP基本数据库链接帮助

[英]PHP basic database link help

i want to fetch a field from database eg. 我想从数据库中获取一个字段,例如。 "name" and then use it as a link to display further info about that name from the database itself i used - “名称”,然后将其用作链接以显示我使用的数据库本身中有关该名称的更多信息-

while($re=mysql_fetch_array($result))
  {

echo"<a href=\"test.php?id=1\">{$re["name"]}'</a>'";

    }

but i want that each 'name' entry when fetched from database be assigned different id like- adam id=1 chris id=2 so that in the next page i can GET that id and display contents accordingly. 但是我希望从数据库中获取的每个“名称”条目都分配不同的ID,例如-Adam ID = 1 chris id = 2,以便在下一页中我可以获取该ID并相应地显示内容。 please help. 请帮忙。

while ($row = mysql_fetch_assoc($result)) {
  echo "<a href=\"test.php?id={$row['id']}\">".htmlspecialchars($row['name'])."</a>\n";
}

Assuming you have an id column in the database, all you need to do is include that field in the results of the SELECT query and echo it along with your existing code. 假设数据库中有一个id列,您要做的就是将该字段包括在SELECT查询的结果中,并将其与现有代码一起回显。

You should have an auto-incrementing primary key in your database that you will use in the SELECT query on your next page, and all you need to do is use this as your id . 您的数据库中应该有一个自动递增的主键,您将在下一页的SELECT查询中使用它,而您所需要做的就是使用它作为id

If you don't have a numeric primary key, add one. 如果您没有数字主键,请添加一个。 If for some reason you can't, use the name field as the id and select by that instead. 如果由于某种原因不能使用,请使用name字段作为id然后选择该name

A couple of side notes: 一些注意事项:

  • Make sure you escape the name field with htmlspecialchars() to ensure you don;t break your output with user entries. 确保使用htmlspecialchars()name字段进行转义,以确保不会用用户输入破坏输出。
  • Use mysql_fetch_assoc() instead of mysql_fetch_array() - this is the right thing to do 99% of the time. 使用mysql_fetch_assoc()而不是mysql_fetch_array() -99%的时间这样做是正确的。
  • You had extra single quotes surrounding your closing </a> - I have removed them in the above example. 您在结束处加上了单引号</a> -在以上示例中,我将其删除了。

It's easier to just use the name itself as the id, and then on the next page use the name as your database query WHERE clause. 仅使用名称本身作为id,然后在下一页将名称用作数据库查询WHERE子句,会更容易。 Since an integer id isn't known to your database, you cannot easily match it back up to the name. 由于您的数据库未知整数ID,因此您无法轻松地将其匹配回名称。

while($re=mysql_fetch_array($result))
{
  $name = $rs['name'];
  echo"<a href='test.php?name='" . urlencode($name) . "'>" . htmlentities($name) . "</a>";
}

On your other page... 在另一页上...

$name = urldecode($_GET['name']);
$name = mysql_real_escape_string($name);
$result = mysql_query("SELECT * FROM table WHERE name='$name');

This assumes, of course, that your names are unique. 当然,这假定您的名字是唯一的。

Editing your current example to keep a count like this: 编辑当前示例以保持这样的计数:

$id = 0;

while($re=mysql_fetch_array($result)) {
     $id++;
     echo"<a href=\"test.php?id={$id}\">{$re["name"]}'</a>'";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM