faqts : Computers : Programming : Languages : PHP : Database Backed Sites : General

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

17 of 19 people (89%) answered Yes
Recently 8 of 10 people (80%) answered Yes


How do you generate an url link to a text field in mysql (ie...php?art_id=2&...etc)

May 22nd, 2002 18:44
Philip Olson, raka k, Onno Benschop,

The Url : 
We do something similar to the following :
    $lang   = $HTTP_GET_VARS['lang'];
    $sql    = "SELECT name,email,url,language 
               FROM   tablename 
               WHERE  language='$lang'";
    $conn   = mysql_connect('host','user','pass');
    if (!$conn) {
        $errors[] = "Could not connect to host";
    $result = mysql_query($sql);
    if (!$result) {
        $errors[] = "Could not run query ($sql)";
    while($row = mysql_fetch_assoc($result)) {
        echo "<h3>$name</h3>";
        echo "URL   : <a href='$url'>$url</a>";
        echo "EMAIL : <a href='mailto:$email'>$email</a>";
In the above example, we get the value of 'lang' via the GET method 
from the url. (note: data from url comes from GET method, just like 
method='GET' in a form.  $HTTP_GET_VARS is a predefined variable that 
stores all GET data, see more info below) 
We end up passing $lang into the SQL query using the SQL WHERE clause.  
We select the name,email,url and language from the table where the 
language column is equal to 'php'.  We connect to mysql, send the query 
and fetch the results.
The while loop is a common way to loop through data, we designate the 
fetched row into an array named $row using mysql_fetch_assoc(), many 
other ways exist to do this.  At that point we'll reference, for 
example, the url as $row['url'].  The part that may be new is the use 
of extract().  It turns the arrays keys into variable names with the 
values assigned to them.  In this case it does this :
    // Using extract() is much cooler (and flexible) then this:
    $name     = $row['name'];
    $email    = $row['email'];
    $url      = $row['url'];
    $language = $row['language'];
I used it in this faqt as it makes things easier/shorter to write 
although seems as though more time was spent to explain its use ;-)
As you've noticed, all it comes down to using variables in your SQL 
Basic SQL Tutorial         :
WHERE explanation          :
Predefined Variables       :
Variables from outside PHP :
Checking Data              :