Reputation: 111
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.
Upvotes: 0
Views: 1494
Reputation: 88697
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:
name
field with htmlspecialchars() to ensure you don;t break your output with user entries.mysql_fetch_array()
- this is the right thing to do 99% of the time.</a>
- I have removed them in the above example.Upvotes: 1
Reputation: 1264
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>'";
}
Upvotes: 0
Reputation: 270775
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.
Upvotes: 0