废话不多说直接上代码
public function insert($table, $data, $keyName, $canRepeatAdd = true)
{
$keyStr = "";
$paramStr = "";
$params = [];
foreach ($data as $key => $value)
{
if (is_array($value) || $key == $keyName)
{
continue;
}
if (!empty($keyStr) && !empty($paramStr))
{
$keyStr .= ", ";
$paramStr .= ", ";
}
if ($value === null)
{
$keyStr .= "`{$key}`";
$paramStr .= "null";
}
else if (strtoupper($value) == "NOW()")
{
$keyStr .= "`{$key}`";
$paramStr .= "NOW()";
}
else if(strpos(strtoupper($value), "FROM_UNIXTIME") !== false)
{
$keyStr .= "`{$key}`";
$paramStr .= "{$value}";
}
else if(strpos(strtoupper($value), "DATE_FORMAT") !== false)
{
$keyStr .= "`{$key}`";
$paramStr .= "{$value}";
}
else if(strpos(strtoupper($value), "DATE_ADD") !== false)
{
$keyStr .= "`{$key}`";
$paramStr .= "{$value}";
}
else if(strtoupper($value) == "UNIX_TIMESTAMP()")
{
$keyStr .= "`{$key}`";
$paramStr .= "UNIX_TIMESTAMP()";
}
else
{
$keyStr .= "`{$key}`";
$paramStr .= "?";
$params[] = $this->format($value);
}
}
$ignore = "";
if(!$canRepeatAdd)
{
$ignore = "IGNORE";
}
$sql = "INSERT {$ignore} INTO {$table} ({$keyStr}) VALUES ({$paramStr})";
if (!Database::$Db->array_params_query($sql, $params))
{
return 0;
}
return Database::$Db->new_identity();
}
调用示例
$this->insert('数据库.表名', 要添加的数据, 主键);
标签:insert,keyStr,value,else,key,strtoupper,封装,PHP,paramStr
From: https://blog.csdn.net/qq_39294511/article/details/136896384