分享一下自己的组装SQL语句的方法
/**
* 组成插入SQL语句
* @param string $table
* @param array $data
* @return bool|string
*/
function insertIntoSql($table = '', $data = array()) {
if (empty($data) || !is_array($data) || empty($table)) {
return false;
}
$sql = 'INSERT INTO ' . $table . '(';
$sql_val = 'values ';
foreach ($data as $key => $value) {
if ($key == 0) {
$s_key = '';
foreach ($value as $s_k => $s_v) {
$s_key .= $s_k . ',';
}
$sql .= rtrim($s_key, ',') . ')';
}
$s_val = '(';
foreach ($value as $val) {
$s_val .= "'" . $val . "',";
}
$sql_val .= rtrim($s_val, ',') . '),';
}
$sql_val = rtrim($sql_val, ',');
$inster_sql = $sql . $sql_val;
return $inster_sql;
}
//使用举例
$goods_data[] = [
//以下的key表示数据表的字段名
'id' => $i,
'category_id' => $category_id,// 分类ID
'goods_name' => $v['name'],// name 商品名称
'price' => $v['min_price'],// min_price 价格
'sale_num' => str_replace('月售', '', $v['month_saled_content']),// month_saled_content 销量
'spec' => $v['skus'][0]['spec'],// sku_label 规格
'img' => $v['picture'],// picture 图片
'addtime' => $time,// picture 图片
];
insertIntoSql('ims_goods_shuxin', $goods_data);