Simple query is giving me a confusing problem

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
AJS1987
Forum Newbie
Posts: 2
Joined: Tue Dec 14, 2010 5:45 pm

Simple query is giving me a confusing problem

Post 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
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Simple query is giving me a confusing problem

Post by McInfo »

No database selected
Error messages really do contain useful information. (Hint: mysql_select_db())
AJS1987
Forum Newbie
Posts: 2
Joined: Tue Dec 14, 2010 5:45 pm

Re: Simple query is giving me a confusing problem

Post 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
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Simple query is giving me a confusing problem

Post 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.
Post Reply