将不同的唯一文件上传到服务器,并将其名称保存到数据库中


Uploading different unique files to the server and their names saved to the database

在开始屏幕重复发布之前,请理解我在这里和谷歌搜索,但可以找到有助于我的情况的东西。即使在我打字的时候,一些接近我需要的东西也是用 asp.net 写的。

这是场景。

我有 5 个不同的唯一文件,每个文件都是数据库上的字段名称。

下面是一个示例标记:

<form id="form1" name="contacts_form" method="post" action="save.php" enctype="multipart/form-data">
..
..
      <td class="td_input_form"><input type="file" name="item1" size="50"></td>
      <td class="td_input_form"><input type="file" name="item2" size="50"></td>
      <td class="td_input_form"><input type="file" name="item3" size="50"></td>
      <td class="td_input_form"><input type="file" name="item4" size="50"></td>
      <td class="td_input_form"><input type="file" name="item5" size="50"></td>
..
..
</form>

我们希望将所有 5 个文件上传到一个名为 uploads 的文件夹中,然后将其文件名以及其他表单字段保存到数据库中。

我在让它工作时遇到问题。

  <?php
// Connect to SQL Server database
include("../Connections/Connect.php")
//This is the directory where images will be saved
$target = "uploads";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];
        if ($file_type!="application/pdf" || $file_type!="image/gif" || $file_type!="image/jpeg") {
         $errors[] 'You can only upload PDFs, JPEGs or GIF files.<br>';
        }
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }   
$name='". ms_escape_string($_POST['nameMember']) ."';
$bandMember='". ms_escape_string($_POST['bandMember']) ."';
$pic1='". ms_escape_string(($_FILES['photo1']['name'])) ."';
$pic2='". ms_escape_string(($_FILES['photo2']['name'])) ."';
$pic3='". ms_escape_string(($_FILES['photo3']['name'])) ."';
$pic4='". ms_escape_string(($_FILES['photo4']['name'])) ."';
$pic5='". ms_escape_string(($_FILES['photo5']['name'])) ."';
$about='". ms_escape_string($_POST['aboutMember'];
$bands='". ms_escape_string($_POST['otherBands']) ."';
//Writes the information to the database
$sql="INSERT INTO tableName (nameMember,bandMember,photo1,photo2,photo3,photo4,photo5,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic1', '$pic2', '$pic3', '$pic4', '$pic5', '$about', '$bands')" ;
$objQuery = sqlsrv_query($conn, $sql);
//Writes the files to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//If all is ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded to the directory and records saved to the database";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
sqlsrv_close($conn);
}
?>

不知何故,我感觉将上传文件代码与要插入数据库的变量混淆了。提前感谢您的帮助。

INSERT INTO bids (BidDate,DueDate,DueTime,BidTitle,BidID,Description,BidIDFile,photo1,SignInSheet,TabSheet,Department,Xcontract,ContactEmail,ContactPhone,NumofBids,AwardDate,AwardRecip1,BidType,LastUpdate,Notes,BidStatus) VALUES ('03/27/2015', '03/27/2015','2:00pm','Test','TTTTTTI9','Testing','524767-3252.htm', '240','Jim Brown','jim.brown@yahoo.com','987-254-3311','3','03/25/2015','Johhny, Carey, Jenny','Property Sales','03/24/2015','Testing notes','1')

我以为您可能希望查看实际的 INSERT 语句和声明。

            $sqlArr['values'][$i]   =   "'".ms_escape_string($_FILES['item']['name'][$i])."'";
            $sqlArr['columns'][]  =   "BidIDFile";
            $sqlArr['columns'][$i+=1]  =  "photo".$i;
            $sqlArr['columns'][]  =   "SignInSheet";
            $sqlArr['columns'][]  =   "TabSheet";
if(isset($sqlArr['columns'])) {
    // Because this is dependent on all images being uploaded properly, you
    // need more validation in your code. This code inserts no matter what.
    $sql="INSERT INTO bids (BidDate,DueDate,DueTime,BidTitle,BidID,Description,".implode(",",$sqlArr['columns']).",Department,Xcontract,ContactEmail,ContactPhone,NumofBids,AwardDate,AwardRecip1,BidType,LastUpdate,Notes,BidStatus)
              VALUES ('$bidDate', '$dueDate','$dueTime','$bidTitle','$bidId','$desc',".implode(",",$sqlArr['values']).", '$dept','$bidContact','$contactEmail','$contactPhone','$numBids','$awardDate','$awardrecip1','$bidType','$lastUpdate','$notes','$status'
)" ;

再指几点。

1、字段名称用单引号引起来。因此,您可能会注意到内爆列不再有单引号。

2,另外,我们希望索引位置从 1 而不是 0 开始,因为照片字段名称以 photo1 开头,...

Array
(
    [txtBidDate] => 03/27/2015
    [txtDueDate] => 03/27/2015
    [txtDueTime] => 2:00pm
    [BidTitle] => Test
    [BidID] => TTTTTTI9
    [Description] => Testing
    [Department] => 240
    [BidContact] => Jim Brown
    [ContactEmail] => jim.brown@yahoo.com
    [ContactPhone] => 987-254-3311
    [NumofBids] => 3
    [txtAwardDate] => 03/25/2015
    [AwardRecip] => Johhny, Carey, Jenny
    [BidType] => Property Sales
    [txtLastUpdate] => 03/24/2015
    [Notes] => Testing  notes
    [Status] => 1
)
Array
(
    [item] => Array
        (
            [name] => Array
                (
                    [0] => 524767-3252.htm
                )
            [type] => Array
                (
                    [0] => text/html
                )
            [tmp_name] => Array
                (
                    [0] => C:'Windows'Temp'phpAB56.tmp
                )
            [error] => Array
                (
                    [0] => 0
                    [1] => 4
                    [2] => 4
                    [3] => 4
                    [4] => 4
                    [5] => 4
                    [6] => 4
                    [7] => 4
                    [8] => 4
                )
            [size] => Array
                (
                    [0] => 60343
                )
        )
)

BidDate  
DueDate  
DueTime  
Project Title  
ID  
Description 
BidIDFILE - file upload
photo1  - file upload 
photo2 - file upload  
photo3  - file upload 
photo4  - file upload 
photo5  - file upload 
photo6 - file upload  
Department  
SignInSheet - file upload  
BidContact  
ContactEmail  
ContactPhone  
NumBidReceived  
TabulationSheet - file upload  
AwardDate  
AwardRecipient  
BidType  
LastUpdate  
Notes  
Status

代码截图上传文件并将记录插入数据库:

$cols = (isset($cols) &

&is_array($cols))? implode(",",$cols):";$vals = (isset($vals) &&is_array($vals))?内爆(",",$vals):";

//echo '<pre>';
//print_r($sql);
//print_r($cols);
//print_r($vals);
//echo '</pre>';
//echo '<br />';
//echo "insert into bids ($cols) values ($vals)";
        sqlsrv_query($conn, $sql);
        echo "Register Completed!<br>";
        header('Location: admin.php');
你搞

砸了很多事情,但这应该是一个工作脚本。除了上述评论外,我还在下面注明了更多信息和关注:

形式

<form id="form1" name="contacts_form" method="post" action="" enctype="multipart/form-data">
      <table>
      <tr>
      <!-- You need to array these. The method you have is too manual 
            You could even use for() to create these -->
      <td class="td_input_form"><input type="file" name="item[]" size="50"></td>
      <td class="td_input_form"><input type="file" name="item[]" size="50"></td>
      <td class="td_input_form"><input type="file" name="item[]" size="50"></td>
      <td class="td_input_form"><input type="file" name="item[]" size="50"></td>
      <td class="td_input_form"><input type="file" name="item[]" size="50"></td>
      </tr>
      </table>
      <input type="submit" value="submit" />
</form>

.PHP

<?php
// I can't check this for you...
include("../Connections/Connect.php");
    // In general, you have no check to see that anything was submitted.
    // That is something you may want to implement or else this script
    // will autoload on page load regardless of $_FILES or $_POST submission
    // You may want to add document root
    $target = $_SERVER['DOCUMENT_ROOT']."/uploads";
    // I am filtering the files incase there are empty uploads
    // You need to have the proper file input name (item)
    $_FILES['item']['name'] =   array_filter($_FILES['item']['name']);
    $_FILES['item']['type'] =   array_filter($_FILES['item']['type']);
    $_FILES['item']['size'] =   array_filter($_FILES['item']['size']);
    $_FILES['item']['tmp_name'] =   array_filter($_FILES['item']['tmp_name']);
    foreach($_FILES['item']['name'] as $i => $value ) {
            $file_name              =   $_FILES['item']['name'][$i];
            $file_size              =   $_FILES['item']['size'][$i];
            $file_tmp               =   $_FILES['item']['tmp_name'][$i];
            $file_type              =   $_FILES['item']['type'][$i];
            $name                   =   ms_escape_string($_POST['nameMember']);
            $bandMember             =   ms_escape_string($_POST['bandMember']);
            $about                  =   ms_escape_string($_POST['aboutMember']);
            $bands                  =   ms_escape_string($_POST['otherBands']);
            $sqlArr['values'][$i]   =   "'".ms_escape_string($_FILES['item']['name'][$i])."'";
            $sqlArr['columns'][$i]  =   "photo".$i;
            // At this point you are only notifying user.
            // You have no code to prevent this limitation. 
            if ($file_type!="application/pdf" || $file_type!="image/gif" || $file_type!="image/jpeg")
                 $errors[] =    'You can only upload PDFs, JPEGs or GIF files.<br>';
            // So far, this is just for notification, you haven't
            // actually done anything about this limitation
            if($file_size > 2097152)
                $errors[]='File size must be less than 2 MB';
            // Makes the folder if not already made.
            if(!is_dir($target))
                mkdir($target,0755,true);
            //Writes the files to the server
            if(move_uploaded_file($_FILES['item']['tmp_name'][$i], $target."/".$file_name)) {
                //If all is ok
                echo "The file ". $file_name. " has been uploaded to the directory and records saved to the database";
            }
            else {
            //Gives and error if its not
            echo "Sorry, there was a problem uploading your file.";
            }
        }
if(isset($sqlArr['columns'])) {
    // Because this is dependent on all images being uploaded properly, you
    // need more validation in your code. This code inserts no matter what.
    $sql="INSERT INTO tableName (nameMember,bandMember,`".implode("`,`",$sqlArr['columns'])."`,aboutMember,otherBands)
VALUES ('$name', '$bandMember',".implode(",",$sqlArr['values']).", '$about', '$bands')" ;
    $objQuery = sqlsrv_query($conn, $sql);
    sqlsrv_close($conn);
} ?>

编辑:有关如何处理帖子和文件的进一步说明,请尝试使用将返回数组以在sql语句中使用的处理函数:

形式:在以下格式中添加此行:

<td class="td_input_form"><input type="file" name="BidIDFile[]"></td>

加工:

function ProcessRequest($request = array())
    {
        // See how many post variables are being sent
        if(count($request) > 0) {
                // Loop through post
                foreach($request as $key => $value) {
                        // Create insert values
                        $insert['vals'][]   =   "'".ms_escape_string($value)."'";
                        // Create insert columns
                        $insert['cols'][]   =   "`".str_replace("txt","",$key)."`";
                        // For good measure, create an update string
                        $insert['update'][] =   "`".str_replace("txt","",$key)."`".' = '."'".ms_escape_string($value)."'";
                        // For modern day binding, you can use this array
                        $insert['bind']['cols'][]           =   "`".$key."`";
                        $insert['bind']['cols_bind'][]      =   ":".$key;
                        $insert['bind']['vals'][":".$key]   =   $value;
                        $insert['bind']['update'][]         =   "`".$key.'` = :'.$key;
                    }
                // If there are cols/values return them
                if(isset($insert))
                    return $insert;
            }
    }
function ProcessFiles($name = 'item',$target = '/uploads')
    {
        $target =   $_SERVER['DOCUMENT_ROOT'].$target;
        // Makes the folder if not already made.
        if(!is_dir($target))
            mkdir($target,0755,true);
        // If the files array has been set
        if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
                // Remove empties
                $_FILES[$name]['name']      =   array_filter($_FILES[$name]['name']);
                $_FILES[$name]['type']      =   array_filter($_FILES[$name]['type']);
                $_FILES[$name]['size']      =   array_filter($_FILES[$name]['size']);
                $_FILES[$name]['tmp_name']  =   array_filter($_FILES[$name]['tmp_name']);
                // You need to differentiate your type array names
                $use_name   =   ($name == 'item')? 'photo':$name;
                // To start at photo1, create an $a value of 1
                $a = 1;
                if(!empty($_FILES[$name]['tmp_name'])) {
                         foreach($_FILES[$name]['name'] as $i => $value ) {
                                $file_name  =   ms_escape_string($_FILES[$name]['name'][$i]);
                                $file_size  =   $_FILES[$name]['size'][$i];
                                $file_tmp   =   $_FILES[$name]['tmp_name'][$i];
                                $file_type  =   $_FILES[$name]['type'][$i];
                                if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $target."/".$file_name)) {
                                        // Format the key values for photo
                                        if($name == 'item')
                                            $arr[$use_name.$a]      =   $file_name;
                                        // Format the key values for others
                                        else
                                            $arr[$use_name] =   $file_name;
                                        $sql                =   ProcessRequest($arr);
                                        // Auto increment the $a value
                                        $a++;
                                    }
                            }
                    }
            }
        if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
            return $sql;
    }
// Process files and post (or array in general)
$sql['post']        =   ProcessRequest($_POST);
$sql['file']        =   ProcessFiles('item');
$sql['BidIDFile']   =   ProcessFiles('BidIDFile');
if(isset($sql['post']['cols']))
    $cols[] =   implode(",",$sql['post']['cols']);
if(isset($sql['file']['cols']))
    $cols[] =   implode(",",$sql['file']['cols']);
if(isset($sql['BidIDFile']['cols']))
    $cols[] =   implode(",",$sql['BidIDFile']['cols']);

if(isset($sql['post']['vals']))
    $vals[] =   implode(",",$sql['post']['vals']);
if(isset($sql['file']['vals']))
    $vals[] =   implode(",",$sql['file']['vals']);
if(isset($sql['BidIDFile']['vals']))
    $vals[] =   implode(",",$sql['BidIDFile']['vals']);
$cols   =   (isset($cols) && is_array($cols))? implode(",",$cols):"";
$vals   =   (isset($vals) && is_array($vals))? implode(",",$vals):"";
echo '<pre>';
print_r($sql);
print_r($cols);
print_r($vals);
echo '</pre>';
echo '<br />';
echo "insert into table ($cols) values ($vals)";

会给你类似的东西(我只放了两个帖子键/值对,这就是为什么只有两个。在您的情况下,会有一系列对):

Array
    (
        [post] => Array
            (
                [vals] => Array
                    (
                        [0] => 'asdfsda'
                        [1] => 'sdfsdfsdf'
                    )
                [cols] => Array
                    (
                        [0] => `BidType`
                        [1] => `BidDate`
                    )
                [update] => Array
                    (
                        [0] => `BidType` = 'asdfsda'
                        [1] => `BidDate` = 'sdfsdfsdf'
                    )
            )
        [file] => Array
            (
                [vals] => Array
                    (
                        [0] => '2015012203932.jpg'
                        [1] => 'a1400by1050.jpg'
                    )
                [cols] => Array
                    (
                        [0] => `photo1`
                        [1] => `photo2`
                    )
                [update] => Array
                    (
                        [0] => `photo1` = '2015012203932.jpg'
                        [1] => `photo2` = 'a1400by1050.jpg'
                    )
            )
        [BidIDFile] => Array
            (
                [vals] => Array
                    (
                        [0] => '87682315.jpg'
                    )
                [cols] => Array
                    (
                        [0] => `BidIDFile`
                    )
                [update] => Array
                    (
                        [0] => `BidIDFile` = '87682315.jpg'
                    )
            )
    )
insert into table (`BidType`,`BidDate`,`photo1`,`photo2`,`BidIDFile`) values ('','','2015012203932.jpg','a1400by1050.jpg','87682315.jpg')