select and echo a single field from mysql db using PHP


Question

Im trying to select the title column from a particular row

$eventid = $_GET['id'];
$field = $_GET['field'];
$result = mysql_query("SELECT $field FROM `events` WHERE `id` = '$eventid' ");
echo $result;

all i get is Resource id #19

How should i do this? What is best method?

1
13
11/20/2009 9:29:39 AM

Accepted Answer

$eventid = $_GET['id'];
$field = $_GET['field'];
$result = mysql_query("SELECT $field FROM `events` WHERE `id` = '$eventid' ");
$row = mysql_fetch_array($result);
echo $row[$field];

but beware of sql injection cause you are using $_GET directly in a query. The danger of injection is particularly bad because there's no database function to escape identifiers. Instead, you need to pass the field through a whitelist or (better still) use a different name externally than the column name and map the external names to column names. Invalid external names would result in an error.

10
1/14/2012 10:17:58 AM

Try this:

echo mysql_result($result, 0);

This is enough because you are only fetching one field of one row.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon