简体   繁体   中英

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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