MySQLl one or multiple parameters in where clause - php

I have a form that user can enter following
Shape = Round, Triangle, Square, Rectangle, Rhombus, Kite, Decagon
Color = Red, Black, Green, Yellow, Blue, White
Size = 1, 2, 3 … 11
And in the databases, there are multiple items with above characteristics
Example red color round with size 5 and another round with black color size 1 so on.
User can select just one or all 3 characteristics and submit the form and I want to show founded results.
Example: if user selected only color results should display all items from selected color no matter the shape or size. And if user select shape and color all items that have selected shape and color.
My question is how can create a query to do this?
Code that I try
if (!empty($_POST["shape"])):
$shape = trim($_POST["shape"]);
else:
$shape = "";
endif;
if (!empty($_POST["color"])):
$color = strtolower(trim($_POST["color"]));
else:
$color = "";
endif;
if (!empty($_POST["size"])):
$size = trim($_POST["size"]);
else:
$size = "";
endif;
SQL = SELECT * FROM items WHERE item_shape = $shape && item_color = $color && item_size = $size
Results always 0 unless I use only one WHERE clause it works like only shape and remove others from the command.
Also, I try changing like this
if (!empty($_POST["shape"])):
$shape = trim($_POST["shape"]);
else:
$shape = " Round, Triangle, Square, Rectangle, Rhombus, Kite, Decagon";
endif;
// changed all post parameters sane wat u did with shape
SQL = SELECT * FROM items WHERE item_shape in ($shape) && item_color in ($color) && item_size = ($size)
How can i achieve this? Appreciate your time.

You can try something like this:
// add as many features as you like to filter in this array
$features = array();
if (!empty($_POST["shape"])):
$features['shape'] = trim($_POST["shape"]);
endif;
if (!empty($_POST["color"])):
$features['color'] = strtolower(trim($_POST["color"]));
endif;
if (!empty($_POST["size"])):
$features['size'] = trim($_POST["size"]);
endif;
$sql = "SELECT * FROM items";
// if there is any feature in the array
if ( ! is_null($features))
{
$i = 0;
$len = count($features);
// check each one of the features
foreach ($features as $feature => $feature_value) {
if ($i == 0)
{
// if the first item, use WHERE
$sql .= ' WHERE ';
} else
{
// else, use &&
$sql .= ' && ';
}
$sql .= 'item_' . $feature . ' = ' . $feature_item;
$i++;
}
}

You could build a dynamic query, mapping the columns names of database with the names sent by form. After use a foreach to check if every element has or not a value if positive create a new element in $new. At last make the WHERE clause with implode() it will glue which element of array with AND key-word.
$fakePost = array('Shape' => '', 'Color' => '', 'Size' =>'2');
$fieldsName = ['Shape' => 'shape_list', 'Round' => 'round_list', 'Size' => 'size_list', 'Color' => 'color_list'];
$new = [];
foreach($fakePost as $k => $v){
if(!empty($v)){
$new[] = $fieldsName[$k] . " = '$v'";
}
}
if(!empty($new)){
echo ' WHERE '. implode(' AND ', $new);
}else{
echo 'please select some value';
}
Output:
WHERE size_list = '2'
or:
WHERE shape_list = 'green' AND size_list = '2'

As i understand your problem below query will give the exact result what you want
$shape = $_POST['shape'])??trim($_POST['shape']) ;
$color = $_POST['color'])??trim($_POST['color']) ;
$size = $_POST['color'])??trim($_POST['color']) ;
$where = array();
if (!empty($shape)) {
$shape_arr = explode(',', $shape);
$temp_shape = '';
foreach ($shape_arr as $key => $value) {
$temp_shape .= "'".$value."',";
}
$temp_shape = rtrim($temp_shape,',');
$where[] = " item_shape IN(".$temp_shape.") ";
}
if (!empty($color)) {
$color_arr = explode(',', $color);
$temp_color = '';
foreach ($color_arr as $key => $value) {
$temp_color .= "'".$value."',";
}
$temp_color = rtrim($temp_color,',');
$where[] = " item_color IN(".$temp_color.") ";
}
if (!empty($size)) {
$where[] = " item_size IN(".$size.") ";
}
$sql = "SELECT * FROM items ";
if(count($where)>0){
$sql .= " WHERE ". implode(" AND ", $where) ;
}

Here would be my version:
getItems.php: Fetch the posted values and call a function for fetching the items based on them (getItems()).
itemsFunctions.php: All functions for handling items could be found in a separate file for reuse.
getItems.php
<?php
require_once 'itemsFunctions.php';
$shape = isset($_POST['shape']) ? trim($_POST['shape']) : '';
$color = isset($_POST['color']) ? strtolower(trim($_POST['color'])) : '';
$size = isset($_POST['size']) ? trim($_POST['size']) : 0;
// Get items.
$items = getItems($shape, $color, $size);
// Do something with the fetched items
// (like display them in a table/grid).
itemsFunctions.php
/**
* Fetch items from items table.
*
* #param string $shape [optional] Item shape.
* #param string $color [optional] Item color.
* #param integer $size [optional] Item size.
* #return array Fetched items.
*/
function getItems($shape = '', $color = '', $size = 0) {
// Array containing the WHERE conditions.
$where = array();
// Add WHERE conditions to array based on the given values.
if (!empty($shape)) {
$where[] = 'item_shape = ' . $shape;
}
if (!empty($color)) {
$where[] = 'item_color = ' . $color;
}
if ($size > 0) {
$where[] = 'item_size = ' . $size;
}
// Build the sql statement.
$sql = sprintf('SELECT * FROM items %s'
, count($where) > 0 ? ' WHERE ' . implode(' AND ', $where) : ''
);
// Run query for fetching items by using the sql statement...
// Fetched items as array.
$items = array(
array(
'item_shape' => 'round',
'item_color' => 'red',
'item_size' => '45',
),
array(
'item_shape' => 'square',
'item_color' => 'blue',
'item_size' => '1258',
),
);
return $items;
}
/**
* Add item to items table.
*
* #param string $shape [optional] Item shape.
* #param string $color [optional] Item color.
* #param integer $size [optional] Item size.
* #return integer Last insert id.
*/
function addItem($shape = '', $color = '', $size = 0) {
//...
}
/**
* Update item in items table.
*
* #param integer $id Item ID.
* #param string $shape [optional] Item shape.
* #param string $color [optional] Item color.
* #param integer $size [optional] Item size.
* #return bool TRUE if updated, FALSE otherwise.
*/
function updateItem($id, $shape = '', $color = '', $size = 0) {
// Validate item ID...
//...
}
/**
* Remove item from items table.
*
* #param integer $id Item ID.
* #return bool TRUE if deleted, FALSE otherwise.
*/
function deleteItem($id) {
// Validate item ID...
//...
}
Notes:
Size should be integer.
I used the function sprintf(). It prints as echo() but it
allows the use of placeholders (%s) as well. I use it a lot in
building complex sql statements.
Recommendation: Use prepared statements in your PHP codes in order to avoid MySQL injection.
Good luck!

Related

Codigniter update every row in table with different ID

I have a configuration table in a database, using CI3.
Each row has a unique ID, as well as a type_name and type_desc.
So as each row has a unique ID, how can I update the entire table using one update_batch query?
I obviously don't want to run a query on each row, so I'm guessing i need to build an array with the values, but how can do this with the where clause somehow within the array?! Confused.
I basically need to do this:
UPDATE check_types
SET type_name = POSTED_TYPE_NAME, type_desc = POSTED_TYPE_DESC
WHERE check_type_id = ???? POSTED_ID?????
The only way I know of to do this is to extend the db driver.
In the core folder create file with name MY_DB_mysqli_driver.php. file name assumes that the subclass_prefix defined in config.php is MY_
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_DB_mysqli_driver extends CI_DB_mysqli_driver
{
final public function __construct($params)
{
parent::__construct($params);
}
/**
* Insert_On_Duplicate_Key_Update_Batch
*
* Compiles batch insert strings and runs the queries
*
* #param string $table Table to insert into
* #param array $set An associative array of insert values
* #param bool $escape Whether to escape values and identifiers
* #return int Number of rows inserted or FALSE on failure
*/
public function insert_on_duplicate_update_batch($table = '', $set = NULL, $escape = NULL)
{
if ($set !== NULL)
{
$this->set_insert_batch($set, '', $escape);
}
if (count($this->qb_set) === 0)
{
// No valid data array. Folds in cases where keys and values did not match up
return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
}
if ($table === '')
{
if (!isset($this->qb_from[0]))
{
return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
}
$table = $this->qb_from[0];
}
// Batch this baby
$affected_rows = 0;
for ($i = 0, $total = count($this->qb_set); $i < $total; $i += 100)
{
$this->query($this->_insert_on_duplicate_key_update_batch($this->protect_identifiers($table, TRUE, $escape, FALSE), $this->qb_keys, array_slice($this->qb_set, $i, 100)));
$affected_rows += $this->affected_rows();
}
$this->_reset_write();
return $affected_rows;
}
/**
* Insert on duplicate key update batch statement
*
* Generates a platform-specific insert string from the supplied data
*
* #param string $table Table name
* #param array $keys INSERT keys
* #param array $values INSERT values
* #return string
*/
private function _insert_on_duplicate_key_update_batch($table, $keys, $values)
{
foreach ($keys as $num => $key)
{
$update_fields[] = $key . '= VALUES(' . $key . ')';
}
return "INSERT INTO " . $table . " (" . implode(', ', $keys) . ") VALUES " . implode(', ', $values) . " ON DUPLICATE KEY UPDATE " . implode(', ', $update_fields);
}
}
You would use it like this:
$sql_array = array();
foreach ($data as $row)
{
$arr = array(
'check_type_id' => $row['check_type_id'],
'type_name' => $row['type_name'],
'type_desc' => $row['type_desc']
);
$sql_array[] = $arr;
}
$this->db->insert_on_duplicate_update_batch('check_types', $sql_array);

create formatted excel spreadsheet with MySQL data and PHP using tables

I am working on exporting data from a MySQL database into an Excel spreadsheet. I have found code for doing this before and it works quite well. It does not format the spreadsheet. It was also the first PHP/MySQL site I created and the data didn't need to be pretty. The current project requires formatted data.
Yesterday, I found an article that may have allowed me to do what I need to do. Like an idiot, I didn't copy the link down. I can't find it today.
Here's my code -
<?php
require_once("includes/connection.php");
require_once("includes/functions.php");
// set $closed to 0 for development
$closed = 0;
//create a sting to allow the user to see if s/he is looking at open or closed items
if ($closed) {
$filename = FILENAME."_closed";
} else {
$filename = FILENAME."_open";
}
// $data will hold the result
$data = '<table>';
// is the row a header?
$th = FALSE;
// define the separator character
$sep = '\t';
// array for keys
$thKey = array();
// are we in the first row?
$firstRow = TRUE;
// create the query
$query = "SELECT ";
$query .= "training_requirements.Training, mechanism.mechName, location.locationName, impacted_employees.groupName, ";
$query .= "training_requirements.DateReceived, training_requirements.DateStart, training_requirements.DateDue, ";
$query .= "requester.lastName, requester.firstName, impact.impactName, training_requirements.TimeNeeded, ";
$query .= "priority.priority, training_requirements.Notes ";
$query .= "FROM ";
$query .= "training_requirements, impact, impacted_employees, location, mechanism, requester, priority ";
$query .= "WHERE impact.impactId = training_requirements.impactId ";
$query .= "AND impacted_employees.groupId = training_requirements.impEmpId ";
$query .= "AND location.locationId = training_requirements.trainLocId ";
$query .= "AND mechanism.mechId = training_requirements.mechId ";
$query .= "AND requester.requesterId = training_requirements.requesterId ";
$query .= "AND priority.id = training_requirements.Priority ";
$query .= "AND training_requirements.Closed = $closed ";
$query .= "AND training_requirements.Deleted = 0";
// run the query
$result = executeQuery($connection, $query);
// process the query
if (mysqli_num_rows($result) > 0) {
while ($resource = mysqli_fetch_assoc($result)) {
if (empty($thKey)) {
foreach($resource as $key => $value) {
$thKey[] = $key;
}
}
$data .= '<tr>';
for ($i = 0; $i < count($resource); $i++) {
if ($firstRow) {
// create the header
for ($j = 0; $j < count($resource); $j++) {
$data .= '<th>';
$data .= $thKey[$j];
$data .= '</th>';
}
$data .= '</tr><tr>';
$firstRow = FALSE;
}
$data .= '<td>';
if (isset($resource[$thKey[$i]])) {
$data .= $resource[$thKey[$i]];
} else {
$data .= ' ';
}
$data .= '</td>';
}
$data .= '</tr>';
}
$data .= '</table>';
echo $data;
}
//header('Content-type: application/excel');
//header("Content-Disposition: attachment; filename={$filename}.xls");
//header("Pragma: no-cache");
//header("Expires: 0");
?>
The code continues on to allow me to display the results in a browser. I get a proper looking table in Firefox. When I un-comment the header statements at the bottom, I get a blank Excel file. No cells, no nothing.
Using Excel 2007(12.0.6715.5000) SP3 MSO (12.0.6721.5000), PHP 5.4.24, and MySQL 5.5.40. Using plugins and libraries is not an option.
Vern
your code is just fech data from MySQL and not make any excel file .
here you are a great class for making execl file
with pure XML code without any extension
<?php
/********************************/
/* Code By Mr Korosh Raoufi */
/* WwW.k2-4u.CoM */
/********************************/
/**
* Simple excel generating from PHP5
*
* #package Utilities
* #license http://www.opensource.org/licenses/mit-license.php
* #author Oliver Schwarz <oliver.schwarz#gmail.com>
* #version 1.0
*/
/**
* Generating excel documents on-the-fly from PHP5
*
* Uses the excel XML-specification to generate a native
* XML document, readable/processable by excel.
*
* #package Utilities
* #subpackage Excel
* #author Oliver Schwarz <oliver.schwarz#vaicon.de>
* #version 1.1
*
* #todo Issue #4: Internet Explorer 7 does not work well with the given header
* #todo Add option to give out first line as header (bold text)
* #todo Add option to give out last line as footer (bold text)
* #todo Add option to write to file
*/
class Excel_XML
{
/**
* Header (of document)
* #var string
*/
private $header = "<?xml version=\"1.0\" encoding=\"%s\"?\>\n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
/**
* Footer (of document)
* #var string
*/
private $footer = "</Workbook>";
/**
* Lines to output in the excel document
* #var array
*/
private $lines = array();
/**
* Used encoding
* #var string
*/
private $sEncoding;
/**
* Convert variable types
* #var boolean
*/
private $bConvertTypes;
/**
* Worksheet title
* #var string
*/
private $sWorksheetTitle;
/**
* Constructor
*
* The constructor allows the setting of some additional
* parameters so that the library may be configured to
* one's needs.
*
* On converting types:
* When set to true, the library tries to identify the type of
* the variable value and set the field specification for Excel
* accordingly. Be careful with article numbers or postcodes
* starting with a '0' (zero)!
*
* #param string $sEncoding Encoding to be used (defaults to UTF-8)
* #param boolean $bConvertTypes Convert variables to field specification
* #param string $sWorksheetTitle Title for the worksheet
*/
public function __construct($sEncoding = 'UTF-8', $bConvertTypes = false, $sWorksheetTitle = 'Table1')
{
$this->bConvertTypes = $bConvertTypes;
$this->setEncoding($sEncoding);
$this->setWorksheetTitle($sWorksheetTitle);
}
/**
* Set encoding
* #param string Encoding type to set
*/
public function setEncoding($sEncoding)
{
$this->sEncoding = $sEncoding;
}
/**
* Set worksheet title
*
* Strips out not allowed characters and trims the
* title to a maximum length of 31.
*
* #param string $title Title for worksheet
*/
public function setWorksheetTitle ($title)
{
$title = preg_replace ("/[\\\|:|\/|\?|\*|\[|\]]/", "", $title);
$title = substr ($title, 0, 31);
$this->sWorksheetTitle = $title;
}
/**
* Add row
*
* Adds a single row to the document. If set to true, self::bConvertTypes
* checks the type of variable and returns the specific field settings
* for the cell.
*
* #param array $array One-dimensional array with row content
*/
private function addRow ($array)
{
$cells = "";
foreach ($array as $k => $v):
$type = 'String';
if ($this->bConvertTypes === true && is_numeric($v)):
$type = 'Number';
endif;
$v = htmlentities($v, ENT_COMPAT, $this->sEncoding);
$cells .= "<Cell><Data ss:Type=\"$type\">" . $v . "</Data></Cell>\n";
endforeach;
$this->lines[] = "<Row>\n" . $cells . "</Row>\n";
}
/**
* Add an array to the document
* #param array 2-dimensional array
*/
public function addArray ($array)
{
foreach ($array as $k => $v)
$this->addRow ($v);
}
/**
* Generate the excel file
* #param string $filename Name of excel file to generate (...xls)
*/
public function generateXML ($filename = 'excel-export')
{
// correct/validate filename
$filename = preg_replace('/[^aA-zZ0-9\_\-]/', '', $filename);
// deliver header (as recommended in php manual)
header("Content-Type: application/vnd.ms-excel; charset=" . $this->sEncoding);
header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");
// print out document to the browser
// need to use stripslashes for the damn ">"
echo stripslashes (sprintf($this->header, $this->sEncoding));
echo "\n<Worksheet ss:Name=\"" . $this->sWorksheetTitle . "\">\n<Table>\n";
foreach ($this->lines as $line)
echo $line;
echo "</Table>\n</Worksheet>\n";
echo $this->footer;
}
}
?>
usage:
$xls = new Excel_XML('UTF-8', false, 'title text');
$data = array(
1 => array ('column1 text', 'coloumn2 text'),
1 => array ('column1 text', 'coloumn2 text'),
1 => array ('column1 text', 'coloumn2 text'),
);
$xls -> addArray($data);
$xls -> generateXML('file Name'); // its print code to browser use requred header to download

PHP Excel export not recognised by office 2007

I have been using stack overflow for a good couple of years but only now made an account because I have never become so stuck that I needed to ask a question (not because I'm smart, because my code is simple!), anyway on to my question;
I am exporting a table in .xls format via PHP with information from a few tables in my MYSQL table. all the information and styling works perfectly. The only problem is that when it opens in office 2007 i get this error message:
"the file you are trying to open, 'export.xls', is a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Are you sure you want to view this file?"
So to sum up, all information is pulled from DB successful and all the styling works - I know this to be true because when I click 'yes' on the dialog box that pops up I see everything laid-out perfectly.
Below is the Excel exporter class:
/**
* Class for generating xml with multiple spreadsheets
* #author Marin Crnković
* #version 0.9
* #update_date 21.01.2009
*/
class excel_xml {
var $xml_data;
var $nl;
var $tab;
var $cols;
var $rows;
var $worksheets;
var $counters;
var $xml;
/**
* Constructor
*/
function excel_xml(){
$this->column_width = 150;
$this->debug = false;
$this->cols = array();
$this->row_array = array();
$this->rows = array();
$this->worksheets = array();
$this->counters = array();
$this->nl = "\n";
$this->tab = "\t";
}
/**
* Set debug
*/
function debug() {
$this->debug = true;
}
/**
* Generate xml
* #returns string
*/
function generate() {
// Create header
$xml = $this->create_header().$this->nl;
// Put all worksheets
$xml .= join('', $this->worksheets).$this->nl;
// Finish with a footer
$xml .= $this->create_footer();
$this->xml = $xml;
return $this->xml;
}
/**
* Create worksheet
* Uppon creating a worksheet, delete counters
* #param string $worksheet_name: name of the worksheet
*/
function create_worksheet($worksheet_name) {
$worksheet = '<Worksheet ss:Name="'.$worksheet_name.'">';
$worksheet .= $this->create_table();
$worksheet .= '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>';
// Unset the counters and rows so you can generate another worksheet table
$this->counters = array();
$this->row_array = array();
$this->rows = '';
// Add generated worksheet to the worksheets array
$this->worksheets[] = $worksheet;
}
/**
* Create table
* #returns string
*/
function create_table() {
// Create rows with the method that automaticaly sets counters for number of columns and rows
$rows = $this->create_rows();
// Table header
$table = '<Table ss:ExpandedColumnCount="'.$this->counters['cols'].'" ss:ExpandedRowCount="'.$this->counters['rows'].'" x:FullColumns="1" x:FullRows="1">'.$this->nl;
// Columns data (width mainly)
for($i = 1; $i <= $this->counters['cols']; $i++) {
$table .= '<Column ss:Index="'.$i.'" ss:Width="'.$this->column_width.'" />'.$this->nl;
}
// Insert all rows
$table .= join('', $rows);
// End table
$table .= '</Table>'.$this->nl;
return $table;
}
/**
* Add another row into the array
* #param mixed $array: array with row cells
* #param mixed $style: default null, if set, adds style to the array
*/
function add_row($array, $style = null) {
if(!is_array($array)) {
// Asume the delimiter is , or ;
$array = str_replace(',', ';', $array);
$array = explode(';', $array);
}
if(!is_null($style)) {
$style_array = array('attach_style' => $style);
$array = array_merge($array, $style_array);
}
$this->row_array[] = $array;
}
/**
* Create rows
* #returns array
*/
function create_rows() {
$row_array = $this->row_array;
if(!is_array($row_array)) return;
$cnt = 0;
$row_cell = array();
foreach($row_array as $row_data) {
$cnt++;
// See if there are styles attached
$style = null;
if($row_data['attach_style']) {
$style = $row_data['attach_style'];
unset($row_data['attach_style']);
}
// Store the counter of rows
$this->counters['rows'] = $cnt;
$cells = '';
$cell_cnt = 0;
foreach($row_data as $key => $cell_data) {
$cell_cnt++;
$cells .= $this->nl.$this->prepare_cell($cell_data, $style);
}
// Store the number of cells in row
$row_cell[$cnt][] = $cell_cnt;
$this->rows[] = '<Row>'.$cells.$this->nl.'</Row>'.$this->nl;
}
// Find out max cells in all rows
$max_cells = max($row_cell);
$this->counters['cols'] = $max_cells[0];
return $this->rows;
}
/**
* Prepare cell
* #param string $cell_data: string for a row cell
* #returns string
*/
function prepare_cell($cell_data, $style = null) {
$str = str_replace("\t", " ", $cell_data); // replace tabs with spaces
$str = str_replace("\r\n", "\n", $str); // replace windows-like new-lines with unix-like
$str = str_replace('"', '""', $str); // escape quotes so we support multiline cells now
preg_match('#\"\"#', $str) ? $str = '"'.$str.'"' : $str; // If there are double doublequotes, encapsulate str in doublequotes
// Formating: bold
if(!is_null($style)) {
$style = ' ss:StyleID="'.$style.'"';
} elseif (preg_match('/^\*([^\*]+)\*$/', $str, $out)) {
$style = ' ss:StyleID="bold"';
$str = $out[1];
}
if (preg_match('/\|([\d]+)$/', $str, $out)) {
$merge = ' ss:MergeAcross="'.$out[1].'"';
$str = str_replace($out[0], '', $str);
}
// Get type
$type = preg_match('/^([\d]+)$/', $str) ? 'Number' : 'String';
return '<Cell'.$style.$merge.'><Data ss:Type="'.$type.'">'.$str.'</Data></Cell>';
}
/**
* Create header
* #returns string
*/
function create_header() {
if (is_array($this->styles)) {
$styles = join('', $this->styles);
}
$header = <<<EOF
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
<DownloadComponents/>
<LocationOfComponents HRef="file:///\\"/>
</OfficeDocumentSettings>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>12525</WindowHeight>
<WindowWidth>15195</WindowWidth>
<WindowTopX>480</WindowTopX>
<WindowTopY>120</WindowTopY>
<ActiveSheet>0</ActiveSheet>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom"/>
<Borders/>
<Font/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
<Style ss:ID="bold">
<Font ss:Bold="1" />
</Style>
$styles
</Styles>
EOF;
return $header;
}
/**
* Add style to the header
* #param string $style_id: id of the style the cells will reference to
* #param array $parameters: array with parameters
*/
function add_style($style_id, $parameters) {
foreach($parameters as $param => $data) {
switch($param) {
case 'size':
$font['ss:Size'] = $data;
break;
case 'font':
$font['ss:FontName'] = $data;
break;
case 'color':
case 'colour':
$font['ss:Color'] = $data;
break;
case 'bgcolor':
$interior['ss:Color'] = $data;
break;
case 'bold':
$font['ss:Bold'] = $data;
break;
case 'italic':
$font['ss:Italic'] = $data;
break;
case 'strike':
$font['ss:StrikeThrough'] = $data;
break;
}
}
if(is_array($interior)) {
foreach($interior as $param => $value) {
$interiors .= ' '.$param.'="'.$value.'"';
}
$interior = '<Interior ss:Pattern="Solid"'.$interiors.' />'.$this->nl;
}
if(is_array($font)) {
foreach($font as $param => $value) {
$fonts .= ' '.$param.'="'.$value.'"';
}
$font = '<Font'.$fonts.' />'.$this->nl;
}
$this->styles[] = '
<Style ss:ID="'.$style_id.'">
'.$interior.$font.'
</Style>';
}
/**
* Create footer
* #returns string
*/
function create_footer() {
return '</Workbook>';
}
/**
* Output as download
*/
function download($filename) {
if(!strlen($this->xml)) $this->generate();
header("Cache-Control: public, must-revalidate");
header("Pragma: no-cache");
header("Content-Length: " .strlen($this->xml) );
header("Content-Type: application/vnd.ms-excel");
if(!$this->debug){
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
} else {
header("Content-Type: text/plain");
}
print $this->xml;
exit;
}
}
And this is my implementation with sensitive information censored;
$excel = new excel_xml();
$header_style = array(
'bold' => 1,
'size' => '14',
'color' => '#FFFFFF',
'bgcolor' => '#4F81BD'
);
$excel->add_style('header', $header_style);
$header_style2 = array(
'bold' => 1,
'color' => '#FFFFFF',
'bgcolor' => '#92d050'
);
$excel->add_style('green', $header_style2);
$header_style3 = array(
'bold' => 1,
'color' => '#FFFFFF',
'bgcolor' => '#c00000'
);
$excel->add_style('error', $header_style3);
$header_style4 = array(
'bold' => 1,
'color' => '#FFFFFF',
'bgcolor' => '#e46d0a'
);
$excel->add_style('orange', $header_style4);
$header_style5 = array(
'bold' => 1,
'color' => '#FFFFFF',
'bgcolor' => '#c00000'
);
$excel->add_style('red', $header_style5);
/**
* Add row and attach the style "header" to it
*/
$excel->add_row(array(
'col1',
'col2',
'col3',
'col4',
'col5'
), 'header');
/**
* Add some rows, if you encapsulate the string inside asterisks,
* they will get bold using the predefined style "bold"
* If you append "|x" where x is a number, that cell will be
* merged with the x following cells
*/
$excel->add_row(array(
$Queried_Info_From_DB1,
$Queried_Info_From_DB2,
$Queried_Info_From_DB3,
$Queried_Info_From_DB4,
$Queried_Info_From_DB5
), 'red');
if(mysql_num_rows($result) == 0){
$excel->add_row(array(
'You have no info to display!|4'
), 'error');
}
/**
* Tell the object to create the worksheet.
* The passed string is the name of the worksheet
*/
$excel->create_worksheet('Your info');
/**
* If you invoke the generate method, you will get the
* XML returned or...
*/
$xml = $excel->generate();
/**
* ... you can pass the whole thing for download with
* the passed string as the filename
*/
$excel->download('Export');
You're writing a file that's spreadsheetML format, not BIFF (.xls) format, so MS Excel will complain at this discrepancy. Try saving it with a file extension of .xml (because that's what you're actually creating)

PHP insert nested arrays into mongoDB

I have a function that updates fine with a single dimensional array, but with a multidimensional array (or nested array) it will not update. the document data, the BSONfield (acts as the find key), and the collection are imputed. Any Idea what i am doing wrong?
Public Static function updateDocument($collection, $BSONfield, $document){
$dbcollection = $db->selectCollection($collection);
$sdata = $document[$BSONfield];
$secureInnerDocument = array();
$secureDocument = array();
if($BSONfield == "_id"){
$sdata = new MongoID($sdata);
unset($document["_id"]);
}
$filter = array($BSONfield=>$sdata);
foreach ($document as $k => $v) {
if (is_array($v)) {
foreach ($v as $sk => $sv) {
$secureInnerDocument[$sk] = Security::secureQuery($sv);
}
$secureDocument[$k] = $secureInnerDocument;
}else{
$secureDocument[$k] = Security::secureQuery($v);
}
}
$dbcollection->update($filter,array('$set'=>$secureDocument));
$objid = (string) $secureDocument['_id'];
return $objid;
}
It translates fairly directly:
db.collection.update(
{fieldNameFilter:'filterValue'},
{$set: {'stringFieldName' : 'newValue'}}
);
Translates to:
$collection->update(
array('fieldNameFilter'=>'filterValue'),
array($set => array('stringFieldName'=>$value))
);
Then there are some flags for multi-row updates, etc. which I'm not showing here, but which are in the PHP and Mongo docs.
You might also want to look at: MongoDB - help with a PHP query
So after fiddling around with is my solution ended up being kind of janky, I deleted the Document then re-create it. Here is the code in case anyone is looking:
/**
* updates document in the collection.
* This function secures the data
*
* #return object ID
* #param string $collection The name of the collection
* #param string $BSONfield The $BSON Field you want to index by
* #param string $document The document contents as an array
*/
Public Static function updateDocument($collection, $BSONfield, $document){
$db = Database::dbConnect();
$collection = Security::secureQuery($collection);
$BSONfield = Security::secureQuery($BSONfield);
$dbcollection = $db->selectCollection($collection);
if(array_key_exists('_id', $document)){
$document["_id"] = new MongoID($document["_id"]);
}
Database::deleteDocument($collection, $BSONfield, $document);
$objid = Database::createDocument($collection, $document);
return $objid;
}
/**
* Deletes a document in the collection.
* This function secures the data
*
* #return Boolean True - if successfully deleted, False if document not found
* #param string $collection The name of the collection
* #param string $BSONfield The $BSON Field you want to index by
* #param string $document The document contents as an array
*/
Public Static function deleteDocument($collection, $BSONfield, $document){
$db = Database::dbConnect();
$collection = Security::secureQuery($collection);
$BSONfield = Security::secureQuery($BSONfield);
$exists = False;
$dbcollection = $db->selectCollection($collection);
$documentList = $dbcollection->find();
$sdata = $document[$BSONfield];
if($BSONfield == "_id"){
$sdata = new MongoID($sdata);
}
foreach ($documentList as $doc) {
$documentID = $doc[$BSONfield];
if ($documentID == $sdata){
$exists = True;
}
}
if ($exists){
$deleted = True;
$filter = array($BSONfield=>$sdata);
$dbcollection->remove($filter,true);
}else{
$deleted = False;
}
return $deleted;
}
/**
* Inserts document into the collection.
* This function secures the data
*
* #return object ID.
* #param string $collection The name of the collection
* #param string $document The document contents as an array
*/
Public Static function createDocument($collection, $document){
$db = Database::dbConnect();
$collection = Security::secureQuery($collection);
$dbcollection = $db->selectCollection($collection);
$secureDocument = array();
$secureInnerDocument = array();
foreach ($document as $k => $v) {
if (is_array($v)) {
foreach ($v as $sk => $sv) {
$secureInnerDocument[$sk] = Security::secureQuery($sv);
}
$secureDocument[$k] = $secureInnerDocument;
}else{
if ($k == '_id'){
$secureDocument[$k] = $v;
}else{
$secureDocument[$k] = Security::secureQuery($v);
}
}
}
$dbcollection->insert($secureDocument);
$objid = (string) $secureDocument['_id'];
return $objid;
}
and how i am securing all the data from injections:
/**
* Secures string to be inputed into a database.
*
* #return Retuns secure string
* #param String $string String to be secured
*/
Public Static Function secureQuery($string){
$secureString = strtr($string, array(
"'" => "0x27",
"\"" => "0x22",
"\\" => "0x5C",
"<" => "0x3C",
">" => "0x3E",
"=" => "0x3D",
"+" => "0x2B",
"&" => "0x26",
"{" => "0x7B",
"}" => "0x7D",
));
return $secureString;
}
/**
* Un-Secures string to be inputed into a database.
*
* #return Retuns unsecure string
* #param String $string String to be un-secured
*/
Public Static Function unsecureQuery($string){
$secureString = strtr($string, array(
"0x27" => "'",
"0x22" => "\"",
"0x5C" => "\\",
"0x3C" => "<",
"0x3E" => ">",
"0x3D" => "=",
"0x2B" => "+",
"0x26" => "&",
"0x7B" => "{",
"0x7D" => "}",
));
return $secureString;
}
enjoy!
You don't seem to be using the $set operator correctly. As per the MongoDB docs, you need to format your update document like so;
{ $set : { field : value } }
If you're running a $set on nested keys, you need to use dot notation to get to them. For example;
{ $set : { field.nest : value } }

How do I redistribute an array into another array of a certain "shape". PHP

I have an array of my inventory (ITEMS A & B)
Items A & B are sold as sets of 1 x A & 2 x B.
The items also have various properties which don't affect how they are distributed into sets.
For example:
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
I want to redistribute the array $inventory to create $set(s) such that
$set[0] => Array
(
[0] => array(A,PINK)
[1] => array(B,RED)
[2] => array(B,BLUE)
)
$set[1] => Array
(
[0] => array(A,MAUVE)
[1] => array(B,YELLOW)
[2] => array(B,GREEN)
)
$set[2] => Array
(
[0] => array(A,ORANGE)
[1] => array(B,BLACK)
[2] => NULL
)
$set[3] => Array
(
[0] => array(A,GREY)
[1] => NULL
[2] => NULL
)
As you can see. The items are redistributed in the order in which they appear in the inventory to create a set of 1 x A & 2 x B. The colour doesn't matter when creating the set. But I need to be able to find out what colour went into which set after the $set array is created. Sets are created until all inventory is exhausted. Where an inventory item doesn't exist to go into a set, a NULL value is inserted.
Thanks in advance!
I've assumed that all A's come before all B's:
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
for($b_start_index = 0;$b_start_index<count($inventory);$b_start_index++) {
if($inventory[$b_start_index][0] == 'B') {
break;
}
}
$set = array();
for($i=0,$j=$b_start_index;$i!=$b_start_index;$i++,$j+=2) {
isset($inventory[$j])?$temp1=$inventory[$j]:$temp1 = null;
isset($inventory[$j+1])?$temp2=$inventory[$j+1]:$temp2 = null;
$set[] = array( $inventory[$i], $temp1, $temp2);
}
To make it easier to use your array, you should make it something like this
$inv['A'] = array(
'PINK',
'MAUVE',
'ORANGE',
'GREY'
);
$inv['B'] = array(
'RED',
'BLUE',
'YELLOW',
'GREEN',
'BLACK'
);
This way you can loop through them separately.
$createdSets = $setsRecord = $bTemp = array();
$bMarker = 1;
$aIndex = $bIndex = 0;
foreach($inv['A'] as $singles){
$bTemp[] = $singles;
$setsRecord[$singles][] = $aIndex;
for($i=$bIndex; $i < ($bMarker*2); ++$i) {
//echo $bIndex.' - '.($bMarker*2).'<br/>';
if(empty($inv['B'][$i])) {
$bTemp[] = 'null';
} else {
$bTemp[] = $inv['B'][$i];
$setsRecord[$inv['B'][$i]][] = $aIndex;
}
}
$createdSets[] = $bTemp;
$bTemp = array();
++$bMarker;
++$aIndex;
$bIndex = $bIndex + 2;
}
echo '<pre>';
print_r($createdSets);
print_r($setsRecord);
echo '</pre>';
To turn your array into an associative array, something like this can be done
<?php
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
$inv = array();
foreach($inventory as $item){
$inv[$item[0]][] = $item[1];
}
echo '<pre>';
print_r($inv);
echo '</pre>';
Maybe you can use this function, assuming that:
... $inventory is already sorted (all A come before B)
... $inventory is a numeric array staring at index zero
// $set is the collection to which the generated sets are appended
// $inventory is your inventory, see the assumptions above
// $aCount - the number of A elements in a set
// $bCount - the number of B elements in a set
function makeSets(array &$sets, array $inventory, $aCount, $bCount) {
// extract $aItems from $inventory and shorten $inventory by $aCount
$aItems = array_splice($inventory, 0, $aCount);
$bItems = array();
// iterate over $inventory until a B item is found
foreach($inventory as $index => $item) {
if($item[0] == 'B') {
// extract $bItems from $inventory and shorten $inventory by $bCount
// break out of foreach loop after that
$bItems = array_splice($inventory, $index, $bCount);
break;
}
}
// append $aItems and $bItems to $sets, padd this array with null if
// less then $aCount + $bCount added
$sets[] = array_pad(array_merge($aItems, $bItems), $aCount + $bCount, null);
// if there are still values left in $inventory, call 'makeSets' again
if(count($inventory) > 0) makeSets($sets, $inventory, $aCount, $bCount);
}
$sets = array();
makeSets($sets, $inventory, 1, 2);
print_r($sets);
Since you mentioned that you dont have that much experience with arrays, here are the links to the php documentation for the functions I used in the above code:
array_splice — Remove a portion of the array and replace it with something else
array_merge — Merge one or more arrays
array_pad — Pad array to the specified length with a value
This code sorts inventory without any assumption on inventory ordering. You can specify pattern (in $aPattern), and order is obeyed. It also fills lacking entries with given default value.
<?php
# config
$aInventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK"),
array("C","cRED"),
array("C","cBLUE"),
array("C","cYELLOW"),
array("C","cGREEN"),
array("C","cBLACK")
);
$aPattern = array('A','B','A','C');
$mDefault = null;
# preparation
$aCounter = array_count_values($aPattern);
$aCurrentCounter = $aCurrentIndex = array_fill_keys(array_unique($aPattern),0);
$aPositions = array();
$aFill = array();
foreach ($aPattern as $nPosition=>$sElement){
$aPositions[$sElement] = array_keys($aPattern, $sElement);
$aFill[$sElement] = array_fill_keys($aPositions[$sElement], $mDefault);
} // foreach
$nTotalLine = count ($aPattern);
$aResult = array();
# main loop
foreach ($aInventory as $aItem){
$sElement = $aItem[0];
$nNeed = $aCounter[$sElement];
$nHas = $aCurrentCounter[$sElement];
if ($nHas == $nNeed){
$aCurrentIndex[$sElement]++;
$aCurrentCounter[$sElement] = 1;
} else {
$aCurrentCounter[$sElement]++;
} // if
$nCurrentIndex = $aCurrentIndex[$sElement];
if (!isset($aResult[$nCurrentIndex])){
$aResult[$nCurrentIndex] = array();
} // if
$nCurrentPosition = $aPositions[$sElement][$aCurrentCounter[$sElement]-1];
$aResult[$nCurrentIndex][$nCurrentPosition] = $aItem;
} // foreach
foreach ($aResult as &$aLine){
if (count($aLine)<$nTotalLine){
foreach ($aPositions as $sElement=>$aElementPositions){
$nCurrentElements = count(array_keys($aLine,$sElement));
if ($aCounter[$sElement] != $nCurrentElements){
$aLine = $aLine + $aFill[$sElement];
} // if
} // foreach
} // if
ksort($aLine);
# add empty items here
} // foreach
# output
var_dump($aResult);
Generic solution that requires you to specify a pattern of the form
$pattern = array('A','B','B');
The output will be in
$result = array();
The code :
// Convert to associative array
$inv = array();
foreach($inventory as $item)
$inv[$item[0]][] = $item[1];
// Position counters : int -> int
$count = array_fill(0, count($pattern),0);
$out = 0; // Number of counters that are "out" == "too far"
// Progression
while($out < count($count))
{
$elem = array();
// Select and increment corresponding counter
foreach($pattern as $i => $pat)
{
$elem[] = $inv[ $pat ][ $count[$i]++ ];
if($count[$i] == count($inv[$pat]))
$out++;
}
$result[] = $elem;
}

Categories