【发布时间】:2011-10-06 20:04:31
【问题描述】:
下面的代码上传多张图片没问题。但是,我试图让它根据循环所在的迭代更新表中的字段。问题:IF 语句在循环时似乎不起作用。 IE。它只会将第一个 file_name 添加到数据库中。
有人看到我在这里做错了吗?如果是的话,非常感谢!!!
for ($i = 1; $i < 4; $i++)
{
/* Handle the file upload */
$upload = $this->upload->do_upload('image' . $i);
/* File failed to upload - continue */
if ($upload === FALSE)
continue;
/* Get the data about the file */
$data = $this->upload->data();
$uploadedFiles[$i] = $data;
if ($i == 1)
{
$filenames1 = array(
'product_image_front' => $data['file_name'],
);
$this->db->where('id', $this->db->insert_id());
$this->db->update('products', $filenames1);
}
if ($i == 2)
{
$filenames2 = array(
'product_image_back' => $data['file_name'],
);
$this->db->where('id', $this->db->insert_id());
$this->db->update('products', $filenames2);
}
if ($i == 3)
{
$filenames3 = array(
'product_image_back' => $data['file_name'],
);
$this->db->where('id', $this->db->insert_id());
$this->db->update('products', $filenames3);
}
}
【问题讨论】:
-
if 语句有 5 个,而不是 3 个。你指的是什么 if 语句?我强烈建议重构代码以将重复的代码放入函数中,否则不必重复。
-
你能在你的
$i==2块内放一个echo "hello world"来检查它是否达到那个点吗?一些提示: 1. 正确缩进你的代码。花括号之间的所有内容都应该像这样缩进另一个级别:pastebin.com/SVFPZ2Tt。它更具可读性。 2. 对$i==2和$i==3使用“else if”。它更高效、更清洁。如果 $i 为 1,您不想费心检查 $i==2 和 $i==3,else if 确保只执行一个。 -
不相关,但据我所知,您不需要 3 个相同的代码块,
if ($i < 4)就足够了。
标签: php codeigniter loops if-statement iteration