尝试构建一个可以插入SQL数据库的函数,无论变量有多少或几乎没有。目前我的功能不起作用。
function insert($table, $columns, $results){
global $dbh;
$results = explode(',',$results);
$val= '';
$ex = '';
foreach($results as $result){
$val .= ":" . $result . ",";
$ex = "':" . $result . "' => $result,";
}
$val = rtrim($val, ',');
$ex = rtrim($ex, ',');
$sql = "INSERT INTO $table ($columns) VALUES ($val)";
$q = $dbh->prepare($sql);
$q->execute(array($ex));
}
这样称呼:insert('users','email,pwd,forename,surname,level,status',$vals);
我在哪里设法使其适用于我的Select功能。
function check($table,$columns,$results){
global $dbh;
$columns = explode(',',$columns);
$results = explode(',',$results);
$whr= '';
$int = 0;
foreach($columns as $column){
$whr.= " AND " . $column . " = '{$results[$int]}'";
$int += 1;
}
$sql = "SELECT * FROM $table WHERE status != 'D' $whr";
$return = 0;
foreach($dbh->query($sql) as $check){
$return = 1;
}
return $return;
}
答案 0 :(得分:0)
这是我使用的方法......
public function iInsert($table,$columns,$values)
{
# prepare the insert statement
$col_str = "(" . implode(",",$columns) . ")";
# is this a set of values or a select statement?
if (is_array($values)){
# this is an array of values
foreach($values as $value){
$cnv_val[] = $this->checkNULL($value);
}
$q = array_fill(0,count($columns),'?');
$val_str = "VALUES (" . implode(",", $q) . ")";
}else{
# assume this is a select statement for insert
$val_str = $values;
}
$syntax_str = "INSERT INTO $table $col_str \r\n$val_str";
# execute the insert
$sth = $this->iExec($syntax_str, $cnv_val, "inserted");
# return the rows affected as a string
return $sth;
}
此示例使用该方法实例化一个类,但是可以帮助您了解...
* INSERT -
* *** iInsert( string $table, array $columns, array [or string] $values ); ***
* Returns: rows affected.
*
* Example 1:
*
* $result_array = $test_db->iInsert( "BIDDING_BASIS_CODES",
* array('BIDDING_BASIS_CODE', 'CODE_DESC', 'CODE_ACTIVE_FLAG', 'IBR_CODE', 'LAST_MOD_BY_USER_ID', 'LAST_MOD_DATE_TIME'),
* array('TEST', 'TEST CODE - DISREGARD','N', 'N', 'cd_boust', '1/1/2011 09:00')
* );
* echo $result;
*
* Example 2:
*
* $result_array = $test_db->iInsert( "BIDDING_BASIS_CODES",
* array('BIDDING_BASIS_CODE', 'CODE_DESC', 'CODE_ACTIVE_FLAG', 'IBR_CODE', 'LAST_MOD_BY_USER_ID', 'LAST_MOD_DATE_TIME'),
* "SELECT
* Row_1,
* Row_2,
* Row_3,
* Row_4,
* Row_5,
* Row_6
* FROM
* tablename"
* );
* echo $result;
答案 1 :(得分:0)
首先,我可能会将您的列和值作为关联数组传递给函数。这有助于强制函数调用者必须传递相同数量的两者。至少你应该有逻辑来比较传入的列和值元素的数量,以确保它们是相等的。您可以尝试这样的事情(注意我也将DB连接作为参数传递,这是更好的编码实践)。
function insert($db, $table, $key_value_array) {
$sql = 'INSERT INTO ' . $table . ' ';
$columns = '(';
$values = '(';
foreach ($key_value_array as $k => $v) {
$columns .= '`' . $k . '`, ';
$values .= "'" . $v . "', ";
}
$columns = rtrim($columns, ', ') . ')';
$values = rtrim($values, ', ') . ')';
$sql .= $columns . ' VALUES ' . $values;
$q = $db->prepare($sql);
$q->execute();
}