Page 1 of 1

1 record to return from SQL query

Posted: Tue Dec 05, 2006 4:33 pm
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?

Posted: Tue Dec 05, 2006 5:20 pm
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.