Click to See Complete Forum and Search --> : Basic MySQL/PHP


aj_nsc
10-21-2006, 10:32 PM
I am a novice in PHP and a complete beginner to MySQL and I have (what I deem to be) a fairly simple question. I am trying to get a single field value out of MySQL...the database structure is below:

Database name = bhwbpast_content
Table name = page_table
Table structure = pageID title contentID

I am trying to get the value for 'title' out of database by referencing pageID, which is the unique value in this database.

When someonw views my site at index.php, the page uses a php script to determine the id ($id) of the script ($id=0 when page equals index.php) and I want to get the title value when the pageID = 0. I call a PHP function that connects to the database (no problems there) and runs the following function:

function getHeaderImage($id) {
$query = "SELECT title FROM page_table WHERE pageID='$id'";
$image = mysql_query($query);

echo "<img src=\"images/header/".$image."\.gif" alt=\"\" />";

}

Where $id is the variable (successfully) passed to the function. However, it echo's "Resource id #6" when I view the page source. Am I missing a step between the $image variable and the echo statement which will turn $image into the actual value???

NogDog
10-21-2006, 11:47 PM
You need to use a mysql_fetch_* function to fetch a result row from the result set, e.g.:

function getHeaderImage($id) {
$query = "SELECT title FROM page_table WHERE pageID='$id'";
$result = mysql_query($query) or die("Query failed ($query): ".mysql_error());
if(mysql_num_rows($result))
{
list($image) = mysql_fetch_assoc($result);
echo "<img src=\"images/header/".$image.".gif" alt=\"\" />";
}
}

aj_nsc
10-22-2006, 08:07 AM
Great, that's the answer I was looking for. Because I'm totally new though, would you mind telling my why there's a result 'set' when I am selecting a single record (remembering 'pageID' is the unique key)?

mark_yieh
10-23-2006, 11:31 AM
When you use mysql_query with SELECT, it will return a resource, not the data in the field itself. A resource is a special variable that points to an external resource and they are used by special functions that will parse these resources. One of those special functions is mysql_fetch_assoc like the example shown NogDog. You can also use mysql_fetch_array, mysql_fetch_row, or mysql_fetch_object, or mysql_result to retrieve the information from the resource that was returned by your query. You can learn more about resources and these individual functions from the PHP resource manual.

http://www.php.net/quickref.php