Wednesday, February 23, 2011

How to Create a Link from a Database?

Often people do our database tutorials, and are able to fetch the information they need and echo it onto a page, but struggle with figuring out how to link their results. This is actually a very simple process. Basically you just echo the appropriate HTML and call the URL in the middle of it. Here are some examples. In this example we are fetching an array and assigning it to $info, and one of the fields holds email addresses.
 while($info = mysql_fetch_array( $data ))
{
Print $info['name'] . "<br> ";
Print "<a href=mailto:".$info['email'] . ">" .$info['email'] . "</a><br>";
}
Notice how we called .$info['email'] twice, once to display the e-mail and once to be used in the link. The actual href linking code is placed around the information using print or echo, and separated with dots.
Here is another example using a web address and website name.
 while($info = mysql_fetch_array( $data ))
{
Print "<a href=".$info['siteurl'] . ">" .$info['sitetitle'] . "</a><br>";
}
Again we first print the <a href= then add a dot to show we are switching gears and now printing something different, in our case the website URL we get from our database array. Finally we add another dot so we can finish our link code </a><br>.
source php.about.com