Php INSERT class function This is a INSERT function. It's working... I just pulled out the function from the class, atm to try it out. And improve. I think the code is a bit messy, And I am pretty sure I can improve the code, less code, for example.. Any ideas?

   $data['test'] = array('username' =&gt; 'john', 
              'password' =&gt; 'hello',
              'userlevel' =&gt; '__d');

$table = 'users';

$numItems = count($data['test']);
$i = 0;

$sql = "INSERT INTO " . $table . "(". implode(", ", array_keys($data['test'])) .")";


$sql .= " VALUES (";

$i = 0;

foreach ($data['test'] as $value) {

    if ($i+1 == $numItems and $value == '__d') {
        $sql .= "" . 'NOW()' . ")";
    } else if ($i+1 == $numItems) {
        $sql .= "'" . $value . "')";
    } else if ($value == '__d') {
        $sql .= "" . 'NOW()' . ", ";
    } else {
        $sql .= "'" . $value . "', ";
    }

            $i++;


}

echo $sql;
This is what you have, cleaned a little

foreach ($data['test'] as $value) {

    if ($value == '__d') {
        $sql .= 'NOW()';
    } else {
        $sql .= "'" . $value . "'";
    }
    $i++; // add before the comparisson
    // make the comparrison at one place
    // if the number != total, then we need a comma.
    if($i != $numItems) $sql .= ',';
}
// always end with a close paren.
$sql .= ')';


But you are better off using implode and replace:

// implode using the quotes and commas.
$values = "'".implode("', '", array_values($values))."'";
// swap out __d for NOW
$sql .= str_replace("'__d'",'NOW()',$values);


Of course, you really need to make sure that you've cleaned all of those values with mysql_real_escape_string.