我是构建上传图片并将其存储到数据库中,我已经可以将很多图片上传到文件夹,但我无法插入上传的所有图片名称,我也不知道如何插入数据库,首先我在发生错误时对下面的代码进行了推荐,其次我不知道如果图像计数不同就把它放在数据库中的查询,例如1-10图像,最后一个问题,如果我查询&# 34; SELECT id ..."我想返回它,是否有方法将其返回到字符串或int?如果我使用row(),它将返回stdClass对象。请帮我, 下面是我的代码:
控制器:
$this->load->library("myupload", "form_validation");
$this->load->model("testModel");
$barangImage = array();
if($this->input->post("formSubmit")) {
$this->form_validation->set_rules("nama", "Nama", "required|trim");
if($this->form_validation->run()) {
$insertData = array(
"nama" => $this->input->post("nama")
);
if($id = $this->testModel->add($insertData)) {
//print_r($id);
if(isset($_FILES) && $image = $this->myupload->uploadFile($_FILES)) {
//$image here is already fill with all images name
if(isset($image["error"]) && $image["error"]) {
echo $image["error"];
}else {
foreach($image as $img) {
$barangImage = array(
"gambar" => $img,
"barangid" => $id
);
}
//but when i put into barangImage,
//it only stored last image name
print_r($barangImage);
//output `Array ( [gambar] => 2.JPG [barangid] => Array ( [id] => 52 ) )`
}
}
if($id = $this->testModel->add_images($barangImage)) {
echo "SUCCESS !!!";
}else {
echo "FAIL INSERT IMAGES!!!";
}
}else {
echo "FAIL INSERT DATA NAMA";
}
}else {
echo "FAIL VALIDASI RUN";
}
}
模特:
public function add($newData){
$this->db->insert("cobabarang", $newData);
$nama = $newData["nama"];
$id = $this->db->query("SELECT id FROM cobabarang WHERE nama = \"$nama\"");
return $id->row_array();
}
public function add_images($newImage) {
//$this->db->insert("cobagambar", $newImage);
$id = $newImage["barangid"]["id"];
$gambar = $newImage["gambar"];
$this->db->query("INSERT INTO cobagambar(barangid, gambar1) VALUES($id, \"$gambar\")");
}
答案 0 :(得分:0)
这里有一个错误:
foreach($image as $img)
{
$barangImage = array(
"gambar" => $img,
"barangid" => $id
);
}
将$barangImage
更改为$barangImage[]
当您将图像放入数据库时,我建议您使用json_encode($barangImage)
,然后使用json_decode($images-json-string)
时使用图片。
答案 1 :(得分:0)
您的server-side-events
循环
foreach
我的猜测是 foreach($image as $img) {
$barangImage = array(
"gambar" => $img //might be img['img'] I guess $img is again an array...you hvae to check that
"barangid" => $id //might be $img['id']check on this too..will be $img['id'] I guess
);
}
又是一个带有一些键的数组。你真的需要检查一下你可以像这样直接调用$img
循环中的插入函数,
foreach
注意:数组 foreach($image as $img) {
$barangImage = array(
"gambar1" => $img['img'], //I guess $img is again an array...you hvae to check that
"barangid" => $img['id'] //check on this too..will be $img['id'] I guess
);
$id = $this->testModel->add_images($barangImage));
}
中的keys
必须是表格中的列名。即
barangImage
只需更改gambar1 and barangid will be your column names. so you can directly use codeIgniter's active records.
功能
add_images