#商品表單
case "opInsert" :
$msg = opInsert();
redirect_header($_SESSION['returnUrl'], 3000, $msg);
exit;
```
2. 函數 ```
###############################
# 新增寫入資料庫
###############################
function opInsert(){
global $db;
print_r($_POST);die();
/*
Array ( [title] => adsfasdf [kind] => 1 [price] => 111 [amount] => 222 [enable] => 1 [choice] => 0 [date] => 2017-11-22 [sort] => 1 [icon] => fa-address-book [summary] => 2222 [content] =>
22222
[token] => $2y$10$2H4r7BEF9XvjYnulx0dGqe3LMCR9flth2eS4YBoD.H0s2Et8ZxRgm [op] => opInsert [sn] => )
*/
}
```
```
#################################################
# 商品新增
#################################################
function opInsert(){
global $db;
#驗證token
verifyToken($_POST['token']);
#過濾
$_POST['title'] = db_CleanVars($_POST['title'], "商品名稱");
$_POST['kind'] = db_CleanVars($_POST['kind'], "類別");
$_POST['price'] = db_CleanVars($_POST['price'], "");//商品價格
$_POST['amount'] = db_CleanVars($_POST['amount'], "");//商品數量
$_POST['enable'] = db_CleanVars($_POST['enable'], "啟用");
$_POST['choice'] = db_CleanVars($_POST['choice'], "精選");
$_POST['date'] = db_CleanVars($_POST['date'], "建立日期");
$_POST['date'] = strtotime($_POST['date']);
$_POST['sort'] = db_CleanVars($_POST['sort'], "排序");
$_POST['icon'] = db_CleanVars($_POST['icon'], "");//圖示
$_POST['summary'] = db_CleanVars($_POST['summary'], "");//商品摘要
$_POST['content'] = db_CleanVars($_POST['content'], "");//商品內容
#寫進資料庫
$sql = "insert into `ugm_p_prod`
(`title`,`kind`,`price`,`amount`,`enable`,`choice`,`date`,`sort`,`icon`,`summary`,`content`) values
('{$_POST['title']}','{$_POST['kind']}','{$_POST['price']}','{$_POST['amount']}','{$_POST['enable']}','{$_POST['choice']}','{$_POST['date']}','{$_POST['sort']}','{$_POST['icon']}','{$_POST['summary']}','{$_POST['content']}')"; //die($sql);
$db->query($sql) or redirect_header("", 3000, $db->error."\n".$sql,true);
$sn = $db->insert_id;
#上傳圖片
if($_FILES and !$_FILES['error']){
$ext_name = strrchr($_FILES['pic']['name'], "."); //取得副檔名 .jpg,請注意有包含點
$rand = substr(md5(uniqid(mt_rand(), 1)), 0, 5);//取得一個5碼亂數
$new_name = $rand ."_".$sn.$ext_name;
$DirName = "prod";
mk_dir(WEB_PATH . "/uploads/{$DirName}");
mk_dir(WEB_PATH . "/uploads/{$DirName}/pic");
if(move_uploaded_file($_FILES['pic']['tmp_name'] , WEB_PATH . "/uploads/{$DirName}/pic/{$new_name}")){
#寫進資料庫
#
$sql = "insert into `ugm_p_files_center`
(`col_name`,`col_sn`,`sort`,`kind`,`file_name`,`file_type`,`file_size`,`description`,`original_filename`,`sub_dir`) values
('{$DirName}','{$sn}','1','img','{$new_name}','{$_FILES['pic']['type']}','{$_FILES['pic']['size']}','{$_POST['title']}','{$_FILES['pic']['name']}','{$DirName}/pic')"; //die($sql);
$db->query($sql) or redirect_header("", 3000, $db->error."\n".$sql,true);
}else{
return "新增商品圖片失敗!!";
}
}
return "新增商品成功!!";
}
```
3. 檢查uploads/prod/pic底下是否有上傳檔案
![](https://www.ugm.com.tw/uploads/tad_book3/image/10602/11/11-1.jpg)
4. 檢查「ugm\_p\_files\_center」是否有「記錄」