How to export image in excel file from mysql database dynamically - phpexcel

I want to export image from mysql database into an excel file using phpexcel.I have done it with static value but can not do it dynamically.
<?php
include ('config.php');
function my_constants(){
$url = 'http://' . $_SERVER['HTTP_HOST'] . "/phpexcel_gd/";
$path = $_SERVER['DOCUMENT_ROOT'] . '/phpexcel_gd/';
define('SITEURL', $url);
define('SITEPATH', str_replace('\\', '/', $path));
}
function report_details($display = null) {
if($display){
$imagePath = SITEURL . "images/";
} else {
$imagePath = SITEPATH . "images/";
}
// $select_query = mysqli_query($conn,"SELECT orderid, image_name,image_path FROM tbl_order_details WHERE orderid = '240419-0001-A1-B1'");
// $select_query_row = mysqli_fetch_array($select_query);
// $orderid = $select_query['orderid'];
// $image_name= $select_query['image_name'];
// $image_path = $select_query['image_path'];
$reportdetails = array(
// array('Image' => $image_path . $image_name,'orderid' => $orderid),
array('BrandIcon' => $imagePath . "github.png",'Comapany' => "Github",'Rank' => "3",'Link' => "https://github.com/"),
array('BrandIcon' => $imagePath . "bootstrap.png",'Comapany' => "Bootstrap",'Rank' => "4",'Link' => "http://getbootstrap.com/"),
array('BrandIcon' => $imagePath . "so-icon.png",'Comapany' => "Stack Overflow",'Rank' => "3",'Link' => "http://stackoverflow.com/"),
);
return $reportdetails;
}
/**
* Create excel by from ajax request
*/
function xlscreation_ajax() {
$reportdetails = report_details();
require_once SITEPATH . 'PHPExcel/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator("user")
->setLastModifiedBy("user")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 0;
// Sheet cells
$cell_definition = array(
'A' => 'BrandIcon',
'B' => 'Company',
'C' => 'Rank',
'D' => 'Link'
);
// Build headers
foreach( $cell_definition as $column => $value )
{
$objPHPExcel->getActiveSheet()->getColumnDimension("{$column}")->setAutoSize(true);
$objPHPExcel->getActiveSheet()->setCellValue( "{$column}1", $value );
}
// Build cells
while( $rowCount < count($reportdetails) ){
$cell = $rowCount + 2;
foreach( $cell_definition as $column => $value ) {
$objPHPExcel->getActiveSheet()->getRowDimension($rowCount + 2)->setRowHeight(35);
switch ($value) {
case 'BrandIcon':
if (file_exists($reportdetails[$rowCount][$value])) {
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Customer Signature');
$objDrawing->setDescription('Customer Signature');
//Path to signature .jpg file
$signature = $reportdetails[$rowCount][$value];
$objDrawing->setPath($signature);
$objDrawing->setOffsetX(25); //setOffsetX works properly
$objDrawing->setOffsetY(10); //setOffsetY works properly
$objDrawing->setCoordinates($column.$cell); //set image to cell
$objDrawing->setWidth(32);
$objDrawing->setHeight(32); //signature height
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet()); //save
} else {
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, "Image not found" );
}
break;
case 'Link':
//set the value of the cell
$objPHPExcel->getActiveSheet()->SetCellValue($column.$cell, $reportdetails[$rowCount][$value]);
//change the data type of the cell
$objPHPExcel->getActiveSheet()->getCell($column.$cell)->setDataType(PHPExcel_Cell_DataType::TYPE_STRING2);
///now set the link
$objPHPExcel->getActiveSheet()->getCell($column.$cell)->getHyperlink()->setUrl(strip_tags($reportdetails[$rowCount][$value]));
break;
default:
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $reportdetails[$rowCount][$value] );
break;
}
}
$rowCount++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$saveExcelToLocalFile = saveExcelToLocalFile($objWriter);
$response = array(
'success' => true,
'filename' => $saveExcelToLocalFile['filename'],
'url' => $saveExcelToLocalFile['filePath']
);
echo json_encode($response);
die();
}
function saveExcelToLocalFile($objWriter) {
$rand = rand(1234, 9898);
$presentDate = date('YmdHis');
$fileName = "report_" . $rand . "_" . $presentDate . ".xlsx";
// make sure you have permission to write to directory
$filePath = SITEPATH . 'reports/' . $fileName;
$objWriter->save($filePath);
$data = array(
'filename' => $fileName,
'filePath' => $filePath
);
return $data;
}
?>
Here the $reportdetails contains the static array. How can I pass the mysql database value to the array dynamically? Please suggest any alternative other than phpexcel.

Related

Woocommerce API thinking image SRC is a different type of file, not a JPG

Example:
["images"]=>
array(6) {
[0]=>
array(2) {
["src"]=>
string(112) "https://nz.tradevine.com/BlobStorage/GetFullPhoto?photoID=3783754511503592459&organisationID=3468490059683634443"
["position"]=>
string(1) "0"
}
The image is https://nz.tradevine.com/BlobStorage/GetFullPhoto?photoID=3783754511503592459&organisationID=3468490059683634443
I get an error: "Error: Invalid image: Sorry, you are not allowed to upload this file type. [woocommerce_api_product_image_upload_error]
I change WP_config file to allow any type of file upload.
define('ALLOW_UNFILTERED_UPLOADS', true);
it trys to upload a file called: GetFullPhoto
no .jpg
and it does not work.
This ust to work fine.
Any ideas?
Because the url doesn't include a file extension in it's name, Wordpress treats it as a file with no extension thus failing the wp_check_filetype_and_ext test.
You can add a filter to add .jpg to the end of a filename if it has no extension and is in fact a jpeg like so
add_filter('wp_handle_sideload_prefilter', 'add_jpg_if_no_extension');
function add_jpg_if_no_extension($file){
if(!pathinfo($file['name'], PATHINFO_EXTENSION) && mime_content_type($file['tmp_name']) == 'image/jpeg'){
$file['name'] .= '.jpg';
}
return $file;
}
EDIT:
A more complete solution to work for all image types
add_filter('wp_handle_sideload_prefilter', 'add_extension_if_none_exists');
function add_extension_if_none_exists($file){
if ( pathinfo( $file['name'], PATHINFO_EXTENSION ) ) {
return $file;
}
$real_mime = wp_get_image_mime( $file['tmp_name'] );
$mime_to_ext = apply_filters(
'getimagesize_mimes_to_exts',
array(
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/bmp' => 'bmp',
'image/tiff' => 'tif',
'image/webp' => 'webp',
)
);
if ( ! empty( $mime_to_ext[ $real_mime ] ) ) {
$file['name'] .= '.' . $mime_to_ext[ $real_mime ];
}
return $file;
}
WordPress determines the image type from filename and the image doesn't have an extension, so you will need to get the image extension using mime_content_type, update the image filename with that extension for saving and set the image mime-type and image extension array at filetype check hook
add_filter(
'wp_check_filetype_and_ext',
function( $filetype_and_ext, $file, $filename, $mimes, $real_mime ) {
$filename_ext = pathinfo( $filename, PATHINFO_EXTENSION );
if ( false === $filetype_and_ext['ext'] && false === $filetype_and_ext['type'] && empty( $filename_ext ) && ! empty( $file ) ) {
$file_mime = #mime_content_type( $file );
$file_ext = mime_to_ext( $file_mime );
if ( in_array( $file_mime, array_values( $mimes ) ) && $file_ext ) {
$filetype_and_ext['ext'] = $file_ext;
$filetype_and_ext['type'] = $file_mime;
$filetype_and_ext['proper_filename'] = $filename . '.' . $file_ext;
}
}
return $filetype_and_ext;
},
1000,
5
);
function mime_to_ext( $mime ) {
$mimes_to_ext = apply_filters(
'getimagesize_mimes_to_exts',
array(
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/bmp' => 'bmp',
'image/tiff' => 'tif',
'image/webp' => 'webp',
)
);
if ( ! empty( $mimes_to_ext[ $mime ] ) ) {
return $mimes_to_ext[ $mime ];
}
return false;
}

Drupal 7 | Import CSV, row by row, into custom table

Assuming I have a CSV like this:
value1,value2
value1,value2
and a table with two columns
column1|column2
how can I programatically import the CSV into the table?
#erier's answer is really good and will get the job done.
As the question is tagged with Drupal 7 I thought I would submit a Drupal custom module method, adapting #erier's answer and prettifying it.
For the basics of a custom module, you can see this simple example.
function custom_module_form($form, &$form_state) {
$form['csv_upload'] = array(
'#type' => 'file',
'#title' => t('Choose a file'),
'#title_display' => 'invisible',
'#size' => 22,
'#upload_validators' => array('file_clean_name' => array()),
);
$form['upload'] = array(
'#type' => 'submit',
'#value' => 'Upload',
);
}
function custom_module_form_validate($form, &$form_state) {
$validators = array('file_validate_extensions' => array('csv'));
// Check for a new uploaded file.
$file = file_save_upload('csv_upload', $validators);
//$file = $form_state['values']['csv_upload'];
if (isset($file)) {
// File upload was attempted.
if ($file) {
// Put the temporary file in form_values so we can save it on submit.
$form_state['values']['csv_upload_file'] = $file;
}
else {
// File upload failed.
form_set_error('csv_upload', t('The file could not be uploaded.'));
}
}
}
function custom_module_submit($form, &$form_state) {
$file = $form_state['values']['csv_upload_file'];
$file->status = FILE_STATUS_PERMANENT;
$file->filename = str_replace(' ', '_', $file->filename);
file_save($file);
$csv_file = file_load($file->fid);
$file = fopen($csv_file->uri, "r");
while(! feof($file))
{
$customer = fgetcsv($file));
db_insert('your_db_table')
->fields(array(
'column1' => $customer[0],
'column2' => $customer[1]
))
->execute();
}
fclose($file);
drupal_set_message('CSV data added to the database');
}
function file_clean_name($file) {
$file->filename = str_replace(' ', '_', $file->filename);
}
That is assuming your question was about a database table.
If you meant into an html table, you can adapt the submit function after $csv_file = file_load($file->fid); like this:
$headers = array('column 1', 'column 2');
$rows = array();
$file = fopen("contacts.csv","r");
while(! feof($file))
{
$customer = fgetcsv($file));
$rows[] = array($customer[0], $customer[1]);
}
fclose($file);
return theme('table', array('header' => $headers, 'rows' => $rows);
Or adapt the two by adding the data to the database and displaying to the screen without a second database hit.
This is what I've come up with - I'm no PHP expert - and it doesn't seem pretty - but it works!
$handle = fopen('/path/to/file/filename.csv', 'r');
$row = fgetcsv($handle);
for ($e = 0; $row = fgetcsv($handle); $e++) {
$record = array();
foreach ($row as $field) {
$record[] = $field;
}
db_insert('your_db_table')
->fields(array(
'column1' => $record[0],
'column2' => $record[1]
))
->execute();
}
fclose($handle);
The table will then look like this:
column1|column2
---------------
value1|value2
value1|value2
This module may help you
https://www.drupal.org/sandbox/draenen/2442165
It requires Feeds but it extends it to work with custom tables (non drupal entities)

How to insert an attachment and update a custom field in a post type in Wordpress

I have a custom post type named ['notifications'] with a custom field named ['attachment'] for all posts in ['notifications'] .
I want user to upload an attachment into the library from the front end
If upload is successful
Get the filename of the attachment
Then update a post in custom post type ['notifications'] by its id
Update custom field ['attachment'] in a post to filename
The meta_key for the custom field is ['_ct_text_57fc8ec4573cd']
This is what I have so far
FOR THE FRONT END
<?php
if (isset($_POST['upload'])) {
if (!empty($_FILES)) {
$file = $_FILES['file'];
$attachment_id = upload_user_file($file);
}
}
?>
<form action="" enctype="multipart/form-data" method="post">
<input name="file" type="file">
</form>
INSIDE FUNCTIONS.PHP
function upload_user_file($file = array()) {
require_once(ABSPATH. 'wp-admin/includes/admin.php');
$file_return = wp_handle_upload($file, array('test_form' => false));
if (isset($file_return['error']) || isset($file_return['upload_error_handler'])) {
return false;
} else {
$filename = $file_return['file'];
$post_ID_attachment = 33;
$attachment = array('post_mime_type' => $file_return['type'],
'post_title' => $post_ID_attachment,
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment($attachment, $file_return['url']);
require_once(ABSPATH. 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
wp_update_attachment_metadata($attachment_id, $attachment_data);
if (0 < intval($attachment_id)) {
return $attachment_id;
}
/* UPDATE ATTACHMENT BELOW*/
update_post_meta($post_ID_attachment, '_ct_text_57fc8ec4573cd', $filename);
}
return false;
}
Not sure if I am doing it correctly.
The code above inserts attachment successfully but it is not updating the custom field in post type ['notifications']
You have a return statement in your function, before update_post_meta query. Try following code:
function upload_user_file($file = array()) {
require_once(ABSPATH. 'wp-admin/includes/admin.php');
$file_return = wp_handle_upload($file, array('test_form' => false));
if (isset($file_return['error']) || isset($file_return['upload_error_handler'])) {
return false;
} else {
$filename = $file_return['file'];
$post_ID_attachment = 33;
$attachment = array('post_mime_type' => $file_return['type'],
'post_title' => $post_ID_attachment,
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment($attachment, $file_return['url']);
require_once(ABSPATH. 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
wp_update_attachment_metadata($attachment_id, $attachment_data);
/* UPDATE ATTACHMENT BELOW*/
update_post_meta($post_ID_attachment, '_ct_text_57fc8ec4573cd', $filename);
if (0 < intval($attachment_id)) {
return $attachment_id;
}
}
return false;
}
Also I'm not sure you need these require_once-s in your code, since it in function.php, everything should be loaded.

Extending WP_List_Table / handling checkbox options in plugin administration

I'm working on a WordPress plugin, and part of that plugin requires extending WP_List_Table and storing any of the items which are checked in that table to an option. I've managed to figure out how to properly setup and display the required table, but how do I handle storing the checked options?
Here's what I've got so far...
class TDBar_List_Table extends WP_List_Table {
// Reference parent constructor
function __construct() {
global $status, $page;
// Set defaults
parent::__construct( array(
'singular' => 'theme',
'plural' => 'themes',
'ajax' => false
));
}
// Set table classes
function get_table_classes() {
return array('widefat', 'wp-list-table', 'themes');
}
// Setup default column
function column_default($item, $column_name) {
switch($column_name) {
case 'Title':
case 'URI':
case'Description':
return $item[$column_name];
default:
return print_r($item, true);
}
}
// Displaying checkboxes!
function column_cb($item) {
return sprintf(
'<input type="checkbox" name="%1$s" id="%2$s" value="checked" />',
//$this->_args['singular'],
$item['Stylesheet'] . '_status',
$item['Stylesheet'] . '_status'
);
}
// Display theme title
function column_title($item) {
return sprintf(
'<strong>%1$s</strong>',
$item['Title']
);
}
// Display theme preview
function column_preview($item) {
if (file_exists(get_theme_root() . '/' . $item['Stylesheet'] . '/screenshot.png')) {
$preview = get_theme_root_uri() . '/' . $item['Stylesheet'] . '/screenshot.png';
} else {
$preview = '';
}
return sprintf(
'<img src="%3$s" style="width: 150px;" />',
$preview,
$item['Title'],
$preview
);
}
// Display theme description
function column_description($item) {
if (isset($item['Version'])) {
$version = 'Version ' . $item['Version'];
if (isset($item['Author']) || isset($item['URI']))
$version .= ' | ';
} else {
$version = '';
}
if (isset($item['Author'])) {
$author = 'By ' . $item['Author'];
if (isset($item['URI']))
$author .= ' | ';
} else {
$author = '';
}
if (isset($item['URI'])) {
$uri = $item['URI'];
} else {
$uri = '';
}
return sprintf(
'<div class="theme-description"><p>%1$s</p></div><div class="second theme-version-author-uri">%2$s%3$s%4$s',
$item['Description'],
$version,
$author,
$uri
);
}
// Setup columns
function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'title' => 'Theme',
'preview' => 'Preview',
'description' => 'Description'
);
return $columns;
}
// Make title column sortable
function get_sortable_columns() {
$sortable_columns = array(
'title' => array('Title', true)
);
return $sortable_columns;
}
// Setup bulk actions
function get_bulk_actions() {
$actions = array(
'update' => 'Update'
);
return $actions;
}
// Handle bulk actions
function process_bulk_action() {
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
if ('update' === $this->current_action()) {
foreach ($themes as $theme) {
if ($theme['Stylesheet'] . '_status' == 'checked') {
// Do stuff - here's the problem
}
}
}
}
// Handle data preparation
function prepare_items() {
// How many records per page?
$per_page = 10;
// Define column headers
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
// Build the array
$this->_column_headers = array($columns, $hidden, $sortable);
// Pass off bulk action
$this->process_bulk_action();
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
// Handle sorting
function usort_reorder($a,$b) {
$orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'Title';
$order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc';
$result = strcmp($a[$orderby], $b[$orderby]);
return ($order === 'asc') ? $result : -$result;
}
usort($themes, 'usort_reorder');
//MAIN STUFF HERE
//for ($i = 0; i < count($themes); $i++) {
//}
// Figure out the current page and how many items there are
$current_page = $this->get_pagenum();
$total_items = count($themes);
// Only show the current page
$themes = array_slice($themes,(($current_page-1)*$per_page),$per_page);
// Display sorted data
$this->items = $themes;
// Register pagination options
$this->set_pagination_args( array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil($total_items/$per_page)
));
}
}
Problem is, I can't get it to save properly. I select the rows I want, hit save and it just resets.
I assume you are talking about the checkboxes in your table listing, so this will be how to process bulk actions.
All you need to do is add two new methods to your class and initialize it in the prepare_items method. I use the code below in one of my plugins to delete or export, but you can just as easily run an update.
/**
* Define our bulk actions
*
* #since 1.2
* #returns array() $actions Bulk actions
*/
function get_bulk_actions() {
$actions = array(
'delete' => __( 'Delete' , 'visual-form-builder'),
'export-all' => __( 'Export All' , 'visual-form-builder'),
'export-selected' => __( 'Export Selected' , 'visual-form-builder')
);
return $actions;
}
/**
* Process our bulk actions
*
* #since 1.2
*/
function process_bulk_action() {
$entry_id = ( is_array( $_REQUEST['entry'] ) ) ? $_REQUEST['entry'] : array( $_REQUEST['entry'] );
if ( 'delete' === $this->current_action() ) {
global $wpdb;
foreach ( $entry_id as $id ) {
$id = absint( $id );
$wpdb->query( "DELETE FROM $this->entries_table_name WHERE entries_id = $id" );
}
}
}
Now, call this method inside prepare_items() like so:
function prepare_items() {
//Do other stuff in here
/* Handle our bulk actions */
$this->process_bulk_action();
}
There's a fantastic helper plugin called Custom List Table Example that makes figuring out the WP_List_Table class much easier.

drupal table with the edit link

I have a table in drupal which displays all the content from a table. I have added an edit link to each record . This link should take the user to the input form which has the values populated in it corresponding to the record. RIght now it is just populating the form with the last row.
For a row x, i need the form populated with the values for record x.
The table is created as
function _MYMODULE_sql_to_table($sql) {
$html = "";
// execute sql
$resource = db_query($sql);
// fetch database results in an array
$results = array();
while ($row = db_fetch_array($resource)) {
$results[] = $row;
$email = $row['p1'];
$comment = $row['p2'];
}
// ensure results exist
if (!count($results)) {
$html .= "Sorry, no results could be found.";
return $html;
}
// create an array to contain all table rows
$rows = array();
// get a list of column headers
$columnNames = array_keys($results[0]);
// loop through results and create table rows
foreach ($results as $key => $data) {
// create row data
$row = array(
'edit' => l(t('Edit'),"admin/content/test/$p1/$p2/Table1", $options=array()),);
// loop through column names
foreach ($columnNames as $c) {
$row[] = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// add row to rows array
$rows[] = $row;
}
// loop through column names and create headers
$header = array();
foreach ($columnNames as $c) {
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// generate table html
$html .= theme('table', $header, $rows);
return $html;
}
// then you can call it in your code...
function _MYMODULE_some_page_callback() {
$html = "";
$sql = "select * from {contactus}";
$html .= _MYMODULE_sql_to_table($sql);
return $html;
}
function display(){
$results = array();
$html = "";
$resource = db_query("select * from contactus");
$output = '';
while($row = db_fetch_array($resource)){
$results[] = $row;
}
if(!count($results)){
$html.= "Unable to display table";
return $html;
}
$rows = array();
$columnNames = array_keys($results[0]);
foreach($results as $key=>$data){
$row = array();
foreach($columnNames as $c){
$row = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
$rows[] = $row;
}
$header = array();
foreach($columnNames as $c){
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
$html .= theme('table', $header, $rows);
return $html;
}
You'll want to have $rows = array(); appear before your while loop. What you're doing is essentially destroying the array and redeclaring it as an empty array on each pass. This is why only the last row is appearing for you.

Resources