1 record to return from SQL query

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
timclaason
Forum Commoner
Posts: 77
Joined: Tue Dec 16, 2003 9:06 am
Location: WI

1 record to return from SQL query

Post by timclaason »

I always end up having a lot of methods in my classes where I'm returning 1 record.

For instance (I'll assume you can anticipate what the methods would actually look like)

Code: Select all

$firstname = $myClass->getFirstName($id);
$lastname = $myClass->getLastName($id);
So, now I have 2 methods. Seems kind of bloated to me.

As a way to save space, I'll sometimes do if statements and add an argument:

Code: Select all

$firstname = $myClass->getName($id, FIRST);
$lastname = $myClass->getName($id, LAST);
So, in the second example, I have 1 method, but the code is still kind of verbose.

I'm kind of thinking I want to start doing something like this on methods that return 1 value:

Code: Select all

$firstname = $myClass->singleValueQuery($tablename, firstname, $id);
$lastname = $myClass->singleValueQuery($tablename, lastname, $id);
Then in the actual method, I could make it look like this:

Code: Select all

function singleValueQuery($tbl, $field) {
  $this->query = "SELECT " . $field . " FROM " . $tbl . " WHERE id=" . $id;
  $this->SQL = mysql_query($this->query, $this->link);
  while($this->row = mysql_fetch_array($this->SQL))
      return $this->row['".$field."']; 
}
Is this a bad idea, or is it something that's kind of standard?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Make sure you quote your strings.

While the calls should only be coming from within your library, I wouldn't assume that everything is kosher with the data passed so I'd suggest running things through your databases' native escaping functionality and sanity check the values for safety's sake. If this isn't apart of your database class, I would suggest it be pushed there.
Post Reply