美好的一天!
我将首先说我刚开始学习PHP,所以请放轻松一下......
基本上,我有一个表单,允许用户上传2张图片(以及完成其他字段)。在提交时,表单调用PHP文件(下面的代码),它基本上将详细信息添加到数据库并将图像上载到文件服务器。这对我想要完成的工作很好。我遇到问题的地方是确认信息。
由于我有2个单独的上传字段,我基本上有2个if语句确认这两个文件已正确上传。我想简化这一点,所以我真的只需要显示1条确认信息。
关于如何简化这一点的任何想法?我认为如果两个文件都成功上传,代码将会显示,如果是,则回显“x”,否则回显“y”。我不太熟悉move_uploaded_file函数,所以我不确定我是否可以在那里使用AND语句......任何想法都会非常感激。
//This is the directory where images will be saved
$target = "path/";
$target = $target . basename($_FILES[controlcreative][name]);
$target2 = "path/";
$target2 = $target2 . basename($_FILES[winnercreative][name]);
$pic=($_FILES['controlcreative']['name']);
$pic2=($_FILES['winnercreative']['name']);
$con=mysqli_connect();
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO experiments (vertical, pagetype, pagename, primarykpitype, primarykpilift, primarysignificant, testobjective, takeawayone, optimizationtype, controlcreative, winnercreative)
VALUES
('$_POST[vertical]','$_POST[pagetype]','$_POST[pagename]','$_POST[primarykpitype]','$_POST[primarykpilift]','$_POST[primarysignificant]','$_POST[testobjective]','$_POST[takeawayone]','$_POST[optimizationtype]','$pic','$pic2')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
//Writes the photo to the server
if(move_uploaded_file($_FILES[controlcreative][tmp_name], $target))
{
//Tells you if its all ok
echo "The file ". basename($_FILES[controlcreative][name]). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
//Writes the photo to the server
if(move_uploaded_file($_FILES[winnercreative][tmp_name], $target2))
{
//Tells you if its all ok
echo "The file ". basename($_FILES[winnercreative][name]). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
mysqli_close($con);
答案 0 :(得分:0)
我循环遍历$_FILES
,这可能会为您节省一些代码并设置错误标记
$error = false;
foreach($_FILES as $name => $file)
{
$target = '/path/to/destination/' . $file['name'];
if(!move_uploaded_file($file['tmp_name'], $target)) $error = true;
}
然后
if(!$error) echo 'All files uploaded';