改进这个插入类函数php

时间:2011-09-28 13:50:18

标签: php insert foreach

我讨厌键入INSERT查询,你总是错过一些东西,并得到语法错误。因此,我想创建自己的功能,让我这样做。这是我到目前为止所得到的:

$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;
嗯,是的。关于如何改进此代码的任何提示?

3 个答案:

答案 0 :(得分:1)

sprintf可以使事情更具可读性

$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();

答案 1 :(得分:1)

<?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;
?>

输出:

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

答案 2 :(得分:0)

$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);