...

View Full Version : Yeah, I suck at writing functions



Xaust
11-06-2012, 10:20 PM
Hey all, new here; no idea where to post. Heh, so I am a failure at writing functions; as I have not studied much on them.. Basically I am trying to make New = 1 and Used = 0 so it will post in place with a simple $coach_meta[$nu].. I know it is easy but hey, I suck.


function coach_meta2 ($nu = '') {

global $dbh;

$output = '';
$coach_meta = coach_meta($data['ID']);
$nu = ($coach_meta['ecpt_newused']);

if ($nu = "New") {

$nu = "1";

}
else
{
if ($nu = "Used") {

$nu = "0";

}

$nu = mysql_query($query);

while($data2 = mysql_fetch_assoc($nu)) {
$output = $data2;
}


}

return $output;

}

Anyone care to help an noob? haha

Fou-Lu
11-06-2012, 11:10 PM
This is php code, so this is definitely the wrong forum.
First, I wouldn't do this:


if ($nu = "New") {

$nu = "1";

}
else
{
if ($nu = "Used") {

$nu = "0";

}

It is bizarre to leave that burden on a function directly unless that's its actual job. Let it have $nu equating to only true and false. Let the caller decide what it considers true and false.
Next, don't do this:


global $dbh;

Globalization is a debugging nightmare. Since they are global they are references, and will autodeclare if they do not exist. Changes out of scope are reflected in every scope, so this makes debugging exceedingly difficult. Unless there is a reason for it such as a locked function signature (used by callbacks in php such as usort, set_error_handler, etc), then always write to pass in a variable instead of globalizing it.

So effectively, we're now down to this:


function coach_meta2($dbh, $nu = false)
{
$output = '';
$coach_meta = coach_meta($data['ID']);
// no, call this something different: $nu = ($coach_meta['ecpt_newused']);
$cm = $coach_meta['ecpt_newused'];
$qry = mysql_query($query); // again, something different
while($data2 = mysql_fetch_assoc($qry))
{
$output = $data2; // this will overwrite $output. If you want to append, use .= instead. If you do not want to append, use a LIMIT on the query and order in reverse. Then pull just the first record
}

return $output;
}


So, we now have a few problems.
- What is $data?
- What is $query?
- What is the purpose of both $nu and $dbh?
- What is the purpose of pulling $coach_meta, and ultimately the $cm I created from it?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum