Entry
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 :
http://www.example.com/index.php?lang=php
We do something similar to the following :
<?php
$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";
exit;
}
mysql_select_db('dbname');
$result = mysql_query($sql);
if (!$result) {
$errors[] = "Could not run query ($sql)";
exit;
}
while($row = mysql_fetch_assoc($result)) {
extract($row);
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
statement.
Basic SQL Tutorial :
http://www.sqlcourse.com/
WHERE explanation :
http://www.oreillynet.com/pub/a/linux/2000/11/03/aboutSQL.html
Predefined Variables :
http://www.php.net/manual/en/language.variables.predefined.php
Variables from outside PHP :
http://www.php.net/manual/en/language.variables.external.php
Checking Data :
http://www.phpbuilder.com/columns/sporty20001102.php3