Page 1 of 1

Simple query is giving me a confusing problem

Posted: Tue Dec 14, 2010 6:13 pm
by AJS1987
Ahoy hoy!

I've read the guidelines for error checking and already had it all in place, but I'm getting no love from my MySQL server over what is a really very simple query. It's kicking my ass and it really shouldn't be.

I'm trying to execute the following code as a page that returns an image called from a database.

Code is as following:

Code: Select all

	error_reporting(E_ALL);
	
	$link = mysql_connect('notmyreal.databasehost.com', 'notmyrealusername', 'notmyrealpassword');
	if (!$link) {die('Could not connect: ' . mysql_error());}
	
	$query = sprintf("SELECT photo FROM djs WHERE djid=%s", $_GET['id']);
	
	$result = mysql_query($query, $link);
	
	if(!$result) { $message = 'Invalid query: ' . mysql_error($link) . "<br/>\n" . 'Whole query: ' . $query; die($message); }
	
	$row = mysql_fetch_assoc($result);
	header("Content-type: image/jpeg");
	print $row['photo'];
Originally I had apostrophes around the table, fields, and values, but was thrown a syntax error. Removed them and now I get:
Invalid query: No database selected
Whole query: SELECT photo FROM djs WHERE djid = 1
I've been out of the game a while but damn...

Any ideas?

-Adam

Re: Simple query is giving me a confusing problem

Posted: Tue Dec 14, 2010 7:04 pm
by McInfo
No database selected
Error messages really do contain useful information. (Hint: mysql_select_db())

Re: Simple query is giving me a confusing problem

Posted: Tue Dec 14, 2010 7:24 pm
by AJS1987
Yeah, just stumbled upon this browsing something else unrelated.

Such a stupid thing to miss. When I started writing the section I pulled up the php.net pages for connecting and querying, and seem to have completely missed the select_db page. Even went down the list of mysql functions to see if there was anything I'd missed and glossed straight past that.

Cheers. I'll try not to post stupid questions that are my own damn fault in future ;)

-Adam

Re: Simple query is giving me a confusing problem

Posted: Tue Dec 14, 2010 8:37 pm
by califdon
Don't worry, Adam, we learn the most when we make stupid errors--mainly how to avoid being stupid in the future. When you're just starting to learn something as complex as PHP and MySQL, there are many details that aren't intuitive, including how to connect to a specific database on a MySQL server. You'll learn. Don't be afraid to come back, but try to remember McInfo's advice: really read what the error messages say. Many times they actually tell you what's wrong.