开发者

Improve this insert class function php

I hate to type the INSERT query, you always miss out with some stuff, and get synt开发者_如何学Pythonax error. Therefor, I want to create my own function, to let me do this. This is what I got so far:

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

$table = 'users';

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

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


$sql .= " VALUES (";

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;

Umm, yeah. Any tips on how I can improve this code?


<?php
//test data
$columns = array(
    'username'=>'john',
    'password'=>'hello',
    'userlevel'=>1,
    'date'=>'__d'
);
$table = 'users';

// replace keys and values with SQL delimeters
foreach($columns as $k=>$v) {
    unset($columns[$k]);

    if ($v != '__d' && !is_int($v))
        $v = "'$v'";

    if ($v == '__d')
        $v = 'NOW()';

    $columns["`$k`"] = $v;
}

// create the query
$sql = sprintf('INSERT INTO %s (%s) VALUES (%s)',
            $table,
            implode(",", array_keys($columns)),
            implode(",", $columns)
       );

echo $sql;
?>

Output:

INSERT INTO users (`username`,`password`,`userlevel`,`date`) VALUES ('john','hello',1,NOW())


sprintf can makes things a lot more readable

$columns = array('username'=>'john', 'password'=>'hello', 'userlevel'=>1, 'date'=>$date);
$table = 'users';

$sql = sprintf(
    "insert into %s(%s) values(%s)",
    $table,
    implode( ',', array_keys( $columns ) ),
    implode( ',', array_map( function($v){ return ':'.$v; }, array_keys( $columns ) ) )
);

$stmnt = $pdo->prepare( $sql );
foreach( $columns as $column => $value ) {
    $stmnt->bindValue( ':'.$column, $value );
}
$stmnt->execute();


$columns = array('username'=>'john', 'password'=>'hello', 'userlevel'=>1, 'date'=>$date);
$table = 'users';

//function here
$sql = "INSERT INTO " . $table . "(". implode(",", array_keys($columns)) .") VALUES ('". implode(",", $columns) ."')";

mysql_query($sql);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜