感谢StackOverflow专家查看我的问题。
首先,有可能之前已经问过这个问题,但我的情况有点独特。所以,请听我说。
当我们的用户想要编辑现有记录时,他们还希望能够在添加新文件之前删除现有的pdf文件。
要显示现有文件,我使用此代码。
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
<a href="http://uploads/'.$result["BidIDFile"].'" target="_blank" onclick="window.open (this.href, \'child\', \'height=800,width=850,scrollbars\'); return false" type="application/octet-stream">'.$result["BidIDFile"].'</a>';
}
</td>
然后要删除此文件,我使用以下代码:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
这很好用。但是,编辑文件指向在这个文件中使用INSERT和UPDATE操作的现有文件(非常感谢rasclatt),我在将两者集成在一起时遇到了问题。
有人可以帮助将这两个文件合并为一个吗?
提前感谢您的协助。
这是INSERT和UPDATE文件:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// 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']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, 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], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to <a href="currentrecs.php">Solicitation screen</a>'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to <a href="currentrecs.php">admin screen</a>'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>