Page 1 of 1

GD image with a query?

Posted: Tue Feb 05, 2008 10:07 am
by chansonmpi
I'm looking to have people be able to pull up an image that will display different text depending on the results of a query. In short, I'd like for them to be able to show how many votes they've received by putting in an image call like "http://www.myserver.com/images/theimage.php?id=1234". For some reason, I can't execute a query within the gd image, I get an error. (The image “http://www.myserver.com/theimage.php” cannot be displayed, because it contains errors.)

Is there any way to do this?

My code for the theimage.php ::

Code: Select all

<?php
	Header ("Content-type: image/png");
	/* Connect to the DB */
	$dbhost = "localhost";
	$dbname = "dbname";
	$dbuser = "dbuser";
	$dbpass = "dbpass";
	
	$query1 = mysql_db_query($dbname, "SELECT votes.user_id, COUNT( votes.vote_id ) AS n, vote_users.id, vote_users.name AS name, vote_users.active FROM votes, vote_users WHERE votes.user_id = vote_users.id AND votes.user_id =112113 GROUP BY votes.user_id ORDER BY n");
	while($result = mysql_fetch_array($query1)) {
	$rating=$result[n];
	//echo($rating);
}
	$img_handle = imageCreateFromPNG("http://www.myserver.com/images/theimage.png");
	$color = ImageColorAllocate ($img_handle, 255, 210, 000);
	$ip = $_SERVER['REMOTE_ADDR'];
	ImageString ($img_handle, 3, 10, 9,  "Your rating is: $rating", $color);
	ImagePng ($img_handle);
	ImageDestroy ($img_handle); 
?>

Thanks,
Caleb

Re: GD image with a query? - FIXED

Posted: Tue Feb 05, 2008 10:32 am
by chansonmpi
I posted too soon. I've figured it out.

First, I modified my .htaccess file to allow png files to act as php. Then I renamed the file with a .png extension. Lastly, I altered the code, moving the header call down below the db query, and now it works like a charm.

Hopefully this is useful to someone else who's trying to do something like this.

Code: Select all

<?php

/* Connect to the DB */
$dbhost = "localhost";
$dbname = "dbname";
$dbuser = "dbuser";
$dbpass = "dbpass";

$query1 = mysql_db_query($dbname, "SELECT votes.user_id, COUNT( votes.vote_id ) AS n, vote_users.id, vote_users.name AS name, vote_users.active FROM votes, vote_users WHERE votes.user_id = vote_users.id AND votes.user_id = $usr GROUP BY votes.user_id ORDER BY n");
while($result = mysql_fetch_array($query1)) {
$rating=$result[n];
}
Header ("Content-type: image/png");
$img_handle = imageCreateFromPNG("http://www.myserver.com/images/theimage.png");
$color = ImageColorAllocate ($img_handle, 255, 210, 000);
$ip = $_SERVER['REMOTE_ADDR'];
ImageString ($img_handle, 3, 10, 9, "Your rating is: $rating", $color);
ImagePng ($img_handle);
ImageDestroy ($img_handle);
?>

Re: GD image with a query?

Posted: Tue Feb 05, 2008 12:34 pm
by JAM
It would be great if you could add a closing php tag to the code aswell. :wink:

Re: GD image with a query?

Posted: Tue Feb 05, 2008 12:47 pm
by chansonmpi

:wink: