PHP basic database link help

Deadly 提交于 2019-12-24 23:50:27

问题


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. please help.


回答1:


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>'";
}



回答2:


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.

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.

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.

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.
  • Use mysql_fetch_assoc() instead of mysql_fetch_array() - this is the right thing to do 99% of the time.
  • You had extra single quotes surrounding your closing </a> - I have removed them in the above example.



回答3:


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. Since an integer id isn't known to your database, you cannot easily match it back up to the name.

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.



来源:https://stackoverflow.com/questions/7257851/php-basic-database-link-help

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!