Blueimp jQuery File Upload Integrated with Database - php

This plugin reads image files on blueimproot/server/php/files on page load. I need to read records from database, and replace 'download' HTML structure with my custom structure. I want to show catalog products, which items are affected by uploading/removing images through this plugin.
I've done this so far:
I changed public function get() { ... } in blueimproot/server/php/upload.class.php to retrieve records from database. This function returns json object.
public function get() {
/* default code of Blueimp
$file_name = isset($_REQUEST['file']) ?
basename(stripslashes($_REQUEST['file'])) : null;
if ($file_name) {
$info = $this->get_file_object($file_name);
} else {
$info = $this->get_file_objects();
}
header('Content-type: application/json');
echo json_encode($info);
*/
include_once('../../../../connection.php');
$id_cat = $_REQUEST['catid'];
$query = "SELECT id, name, price, img_path FROM products WHERE id_cat = $id_cat ORDER BY id";
$prods = mysql_query($query);
$prod_arr = array();
while($prod = mysql_fetch_assoc($prods)) {
$prod_arr[] = $prod;
}
header('Content-type: application/json');
echo json_encode($info);
}
I found that function is called from index.php in blueimproot/server/php:
switch ($_SERVER['REQUEST_METHOD']) {
...
case 'GET':
$upload_handler->get();
break;
...
}
I don't know where the returned json object is processed to show to UI. Have been 2 days and still can't track that function flow. Please help. Thanks.
Original Online Demo:
http://blueimp.github.com/jQuery-File-Upload/
Original Plugin Download:
https://github.com/blueimp/jQuery-File-Upload/downloads

My suggestion is to open up the Network Tab in Firebug and watch for any GET requests to server/php/index.php. If it happens after a specific event then you'll have a better idea of where you should look.
I did look through the source files and the only GET request I found was in main.js
$('#fileupload').each(function () {
var that = this;
$.getJSON(this.action, function (result) {
if (result && result.length) {
$(that).fileupload('option', 'done')
.call(that, null, {result: result});
}
});
});
}

public function get() {
/*
$file_name = isset($_REQUEST['file']) ?
basename(stripslashes($_REQUEST['file'])) : null;
if ($file_name) {
$info = $this->get_file_object($file_name);
} else {
$info = $this->get_file_objects();
}
header('Content-type: application/json');
echo json_encode($info);
*/
$id_cat = $_REQUEST['catid'];
$query = "SELECT id, name, price, img_path FROM products WHERE id_cat = $id_cat ORDER BY id";
$prods = mysql_query($query);
$prod_arr = array();
while($prod = mysql_fetch_assoc($prods)) {
//$prod_arr[] = $prod;
$file = new stdClass();
$file->name = "";// here image name goes i do not find image name in your select query
$file->size = filesize($prod["img_path"]);// should be complete path
$file->url = $prod["img_path"];// should be relative path (http://localhost/images/234.jpg)
$file->thumbnail_url = $prod["img_path"]; // thumbnail path
$this->delete_type = "DELETE";
$this->delete_url = ""; //here delete url you can delete image from database
array_push($prod_arr,$file);
}
header('Content-type: application/json');
echo json_encode($prod_arr);
}

Following this WIKI: https://github.com/blueimp/jQuery-File-Upload/wiki/Working-with-databases
I setup uploads to be inserted into a database, then i changed my GET function as follows:
public function get() {
$uploads = $this->query_db();
header('Content-type: application/json');
echo json_encode($uploads);
}
and my query_db function as follows:
public function query_db() {
$uploads_array = array();
$select_result = $this->query("SELECT * FROM `uploads` ORDER BY `file_name`") or die(mysql_error());
while($query_results = mysql_fetch_object($select_result))
{
$file = new stdClass();
$file->id = $query_results->id;
$file->name = $query_results->file_name;
$file->size = $query_results->file_size;
$file->type = $query_results->file_type;
$file->url = "http://files.domain.com/".$query_results->file_name;
$file->thumbnail_url = "http://thumbnails.domain.com/".$query_results->file_name;
$file->delete_url = "";
$file->delete_type = "DELETE";
array_push($uploads_array,$file);
}
return $uploads_array;
}

Related

Query result to a collection of object

I have a database phpmyadmin, I created a class :
<?php
class Ticket
{
private $NumDossier = 0;
private $NomTicket ="";
private $Service = "" ;
private $Impact = 0;
private $Urgence = "";
private $DateOuverture = "";
public function __construct($p_NumDossier, $p_NomTicket,$p_Service,$p_Impact,$p_Urgence,$p_DateOuverture)
{
$this->NumDossier = $p_NumDossier;
$this->NomTicket = $p_NomTicket;
$this->Service = $p_Service;
$this->Impact = $p_Impact;
$this->Urgence = $p_Urgence;
$this->DateOuverture = $p_DateOuverture;
}
public function getNumDossier()
{
return $this->NumDossier;
}
public function getNomTicket()
{
return $this->NomTicket;
}
public function getService()
{
return $this->Service;
}
public function getImpact()
{
return $this->Impact;
}public function getUrgence()
{
return $this->Urgence;
}
public function getDateOuverture()
{
return $this->DateOuverture;
}
}
?>
For all row that my query return I want to create an object and add it to a collection.
My code :
$connexion = cnx();
if($connexion) {
$requete="SELECT * FROM ticket '";
$result = mysqli_query($connexion, $requete);
$result = mysqli_query($connexion, $requete);
$row = mysqli_fetch_assoc($result);
}
$test = new Ticket(0,"","",0,"","");
while($row) {
//create object for each line and add it to an collection
}
If you have a solution/lead me to this issue.
Thanks for read !
I have to assume that the beginning part of your code is correct, so I copied that. But I changed it further on. You want to retrieve multiple rows, so I put the mysqli_fetch_assoc inside the while loop. With each new row I create a new ticket and put it in a 'collection' array.
$connection = cnx();
if ($connexion) {
$query ="SELECT * FROM ticket";
$result = mysqli_query($connection, $query);
if ($result === false) die("The query [$query] could not be executed.");
$collection = [];
while($row = mysqli_fetch_assoc($result)) {
$collection[] = new Ticket($row["NumDossier"],
$row["NomTicket"],
$row["Service"],
$row["Impact"],
$row["Urgence"],
$row["DateOuverture"]);
}
echo "<pre>";
print_r($collection);
echo "</pre>";
}
So I used a simple array for the collection. I used the default numeric array indexing because I wouldn't know what to replace it with. $row["NomTicket"] seems a logical choice.

Update query not working if added the code to update image and pdf

Update query not working if added the code to upload image and pdf. I have the same code for insert and update except prepare and execute, insert query works very fine, update query doesn't. I have also included enctype="multipart/form-data" in the form so that I can get data from $_FILES as well. Moreover, I have used $_FILES['photo']['tmp_name'] and $_FILES['pdf']['tmp_name'] in order to move them using function move_uploaded_file move_uploaded_file($_FILES['photo']['tmp_name'], 'destination'); and move_uploaded_file($_FILES['pdf']['tmp_name'], 'destination');
function edit_profile($pid)
{
if($_SERVER['REQUEST_METHOD']=='POST')
{
echo "<pre>";
print_r($_POST);
print_r($_FILES);
echo "</pre>";
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$sel_post = $_POST['sel_post'];
$txt_post = $_POST['post'];
$post = "";
if(empty($txt_post))
{
$post = $sel_post;
}
else
{
$post = $this->add_new_post($txt_post);
}
if(empty($fullname) || empty($contact))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['photo']['name']))
{
$photo = $_FILES['photo'];
$allowed_ext = array('png','jpg', 'pdf','jpeg', 'bmp', 'gif');
$allowed_size = 20000000;
$tmp_photo = $photo['tmp_name'];
$photo_size = $photo['size'];
$photo_error = $photo['error'];
$photo_ext = explode('.',$photo['name']);
$photo_ext = strtolower(end($photo_ext));
if(in_array($photo_ext,$allowed_ext))
{
if($photo_size <= $allowed_size)
{
$photo_new_name = time()."_".uniqid('',true).'.'.$photo_ext;
$upload_destination = './cdn/uploads/profile/'.$photo_new_name;
if(move_uploaded_file($tmp_photo,$upload_destination))
{
$photo_to_db = $photo_new_name;
}
else
{
array_push($this->errors, STORAGE_ERROR);
return;
}
}
else
{
array_push($this->errors, $document_name.' : '.FILE_SIZE_ERROR);
return;
}
}
else
{
array_push($this->errors, $photo_ext.' : '.FILE_EXT_ERROR);
return;
}
}
if(!empty($_FILES['pdf']['name']))
{
$pdf = $_FILES['pdf'];
$allowed_pdf_ext = array('pdf');
$allowed_pdf_size = 20000000;
$tmp_pdf = $pdf['tmp_name'];
$pdf_size = $pdf['size'];
$pdf_error = $pdf['error'];
$pdf_ext = explode('.',$pdf['name']);
$pdf_ext = strtolower(end($pdf_ext));
if(in_array($pdf_ext,$allowed_pdf_ext))
{
if($photo_size <= $allowed_pdf_size)
{
$pdf_new_name = time()."_".uniqid('',true).'.'.$pdf_ext;
$upload_pdf_destination = './cdn/uploads/profile_pdf/'.$pdf_new_name;
if(move_uploaded_file($tmp_pdf,$upload_pdf_destination))
{
$pdf_to_db = $pdf_new_name;
}
else
{
array_push($this->errors, STORAGE_ERROR);
return;
}
}
else
{
array_push($this->errors, $document_name.' : '.FILE_SIZE_ERROR);
return;
}
}
else
{
array_push($this->errors, $photo_ext.' : '.FILE_EXT_ERROR);
return;
}
}
$statement = $this->db->prepare("UPDATE `profiles` SET `fullname`=?,`email`=?,`contact`=?,`post`=?, `photo`=?, `pdf`=? WHERE `pid`=?");
if($statement->execute([$fullname,$email,$contact,$post,$pid, $pdf_to_db, $photo_to_db]))
{
ExitThis::send_to(URL.'profile/view_profile?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
}
The above code will return me to the view_profile page as if the update query worked properly, however, the data remains the same before the update -- no change.
Edit: After debugging $statement before executing it get this:
PDOStatement Object
(
[queryString] => UPDATE `profiles` SET `fullname`=?,`email`=?,`contact`=?,`post`=?, `photo`=?, `pdf`=? WHERE `pid`=?
)
This issue is might be the wrong sequence of parameters passed, try by following sequence:
if($statement->execute([$fullname,$email,$contact,$post,$photo_to_db,$pdf_to_db,$pid]))
You pass variables to execute method using wrong order.
...db->prepare("UPDATE `profiles` SET `fullname`=?,`email`=?,`contact`=?,`post`=?, `photo`=?, `pdf`=? WHERE `pid`=?");
And next you calls execute with these variables:
...->execute([$fullname,$email,$contact,$post,$pid, $pdf_to_db, $photo_to_db]))
Last 3 should be like $photo_to_db, $pdf_to_db, $pid.
You pass wrong pid, so that's why you don't see update result.
Also you can use named parameters: http://php.net/manual/en/pdostatement.execute.php#example-1072
$statement = $this->db->prepare("UPDATE `profiles` SET
`fullname`=?,`email`=?,`contact`=?,`post`=?, `photo`=?, `pdf`=? WHERE
`pid`=?");
if($statement->execute([$fullname,$email,$contact,$post,$photo_to_db
$pdf_to_db,$pid]))
{
ExitThis::send_to(URL.'profile/view_profile?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
remove $pid on your update statement and also check your parameters please try this code

Search function doesn't show anything

I'm trying for a search function, I made a public function in a file called Topic, and I tried calling the method in the index.php, however it doesn't show anything, I think the problem lies with the while statement, but i'm not entirely sure.
Topic.php
class Topic{
public function searchPosts($postTags)
{
$conn = Db::getInstance();
$statementSearch = $conn->prepare("SELECT * FROM topics INNER JOIN posttopic ON topics.topicID=posttopic.topicID INNER JOIN posts ON posttopic.postID=posts.postID WHERE naam = :naam");
$statementSearch->bindValue(":naam", $postTags);
return $statementSearch->execute(array());
}
}
Index.php
spl_autoload_register(function ($class) {
include_once("classes/" . $class . ".php");
});
$_SESSION['KEYWORD'] = array();
$postArray = array();
//$allResults2 = array();
if (isset($_POST['Find'])) {
if (!empty($_POST['Find'])) {
$searchTopic = new Topic();
$postTags = $_POST['naam'];
$searchTopic->searchPosts($postTags);
while ($row = $statementSearch->fetch(PDO::FETCH_ASSOC)) {
$_SESSION['KEYWORD'][] = $row['postImageUrl'];
$postArray[] = $row['postID'];
}
}
if (count($_SESSION['KEYWORD']) === 0) {
$error = "Sorry no results!";
}
}
This is the html where it should be printed.
<?php
foreach (array_combine($_SESSION['KEYWORD'], $postArray) as $imageLink => $i) {
echo "<a href='./pin.php?postid=$i' ><img src='" . $imageLink . "'</a>";
}
?>

php - contao - saving my model leaves me an empty model

I am programming a Module for Contao in php.
I am using the function "Model::save()", which saves my data to the database.
But when I am trying to use the model after saving, it's just empty. I have no idea how this can happen.
The Code Snippet:
$report->tstamp = time();
$report->machine_id = $machine_data['type_of_machine'];
var_dump($report);
echo "<br/>";
$report->save();
var_dump($report);
echo "<br/>";
So in the var_dump before I save, everything is fine, but the second one doesn't show any data!
Does anybody got some ideas?
Edit2:
OK, here the complete code of the Module:
<?php
use Contao\Date;
use Contao\FilesModel;
use Contao\Input;
use Contao\Module;
use Contao\PageModel;
use Contao\RequestToken;
use Contao\Validator;
class ModuleReportData extends Module
{
protected $strTemplate = 'mod__reportdata';
public function generate()
{
if (TL_MODE == 'BE')
{
/** #var \BackendTemplate|object $objTemplate */
$objTemplate = new \BackendTemplate('be_wildcard');
$objTemplate->wildcard = '### ReportData ###';
$objTemplate->href = 'contao/main.php?do=themes&table=tl_module&act=edit&id=' . $this->id;
return $objTemplate->parse();
}
return parent::generate();
}
public function compile()
{
$report_id = Input::get('r');
if($report_id){
$report = ReportModel::findByPk($report_id);
$project = ProjectModel::findBy('report_id', $report_id);
}else{
$report = new ReportModel();
$project = new ProjectModel();
}
$machine = new MachineModel();
$machines = [];
$next_step = false;
//get data for selectbox machines
$result = $this->Database->prepare("SELECT * FROM tl_sa_machines")->execute();
while($result->next())
{
$id = $result->id;
$machines[$id] = $result->type;
}
//Check if form was submitted
if(Input::post('submit_data')){
$report_data = Input::post('report_data');
$project_data = Input::post('project_data');
$machine_data = Input::post('machine_data');
$errors = [];
$next_step = true;
foreach($report_data as $key => $data)
{
if(empty($data)) continue;
switch ($key) {
case 'document_date':
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $data)) //###andere Formate hinzufügen
{
break;
}
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'customer':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'city':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'country':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'document_version':
if(Validator::isNumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'author':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'max_speed':
if(Validator::isNumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
}
}
$report->setRow($report_data);
foreach($project_data as $key => $data)
{
if(empty($data)) continue;
if(Validator::isAlphanumeric($data)) continue;
else {
$next_step = false;
$errors[$key] = "Error";
}
}
$project->setRow($project_data);
if($next_step)
{
$project->date_of_evaluation = strtotime($project->date_of_evaluation);
$report->document_date = strtotime($report->document_date);
//save and set report_data
$report->tstamp = time();
$report->machine_id = $machine_data['type_of_machine'];
var_dump($report);
echo "<br/>";
$report->save();
var_dump($report);
echo "<br/>";
$report = ReportModel::findByPK($report_id);
var_dump($report);
//save and set project_data
$project->report_id = $report->id;
$project->tstamp = time();
$project->save();
//session for transfering report_id to the next page
/* var_dump($report->id);
var_dump($report_id);
var_dump($project->report_id);
if($report_id) {
$_SESSION['report_id'] = $report_id;
}
else
{//var_dump($report_id);
//var_dump($report->id);
$report_id = $report->id;
$_SESSION['report_id'] = $report_id;
}
$jumpTo = PageModel::findByPk($this->jumpTo);
$url = $this->generateFrontendUrl($jumpTo->row());
$this->redirect($url);*/
}
}
$this->Template->report = $report;
$this->Template->project = $project;
$this->Template->machine = $machine;
$this->Template->machines = $machines;
$this->Template->errors = $errors;
$this->Template->request_token = RequestToken::get();
}
}
I have a form, to save new data, or to edit existing data. There are two different tables in the database I am trying to fill with data. FOr second one I need the new ID of the new row generated in this code. But it doesn't work because the model is empty after saving.
Edit3:
ProjectModel is just that simple:
use Contao\Model;
class ProjectModel extends Model{
protected static $strTable = "tl_sa_projects";
}
I just found out, it only happens when I use the save method on $report. It's working fine with $project!
Update:
It looks like I get an error when the refresh() method tries to select the new inserted databaserow with:
public function refresh()
{
$intPk = $this->{static::$strPk};
// Track primary key changes
if (isset($this->arrModified[static::$strPk]))
{
$intPk = $this->arrModified[static::$strPk];
}
// Reload the database record
$res = \Database::getInstance()->prepare("SELECT * FROM " . static::$strTable . " WHERE " . static::$strPk . "=?")
->execute($intPk);
var_dump($res);
$this->setRow($res->row());
}
Update 2:
Ok the problem is, that the "arrModified" contains an empty string as ID. Does anybody know where this array gets its elements?
Not the answer to your original question, but you should use
ProjectModel::findOneBy('report_id', $report_id);
instead of
ProjectModel::findBy('report_id', $report_id);
since you want to find only one specific project. findBy returns a Contao\Model\Collection (i.e. potentially multiple results) whereas findOneBy returns a Contao\Model.
Update:
Furthermore, your usage of setData and mergeRow is probably not intended this way. You should instead use
foreach ($project_data as $key => $val)
{
$project->$key = $val;
}
for instance.

How do I modify an existing file to add the ability to unlink a specific file from a folder?

Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<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)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// 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));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?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 Solicitation screen'));
$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 admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>

Categories