I want to generate excel report from php,in which there are two images for each row. But the generated excel sheet show images only for the first row.
following is my used code
$pixels = 120;
$points = PHPExcel_Shared_Drawing::pixelsToPoints($pixels);
$wpixels = 95;
$wpoints = PHPExcel_Shared_Drawing::pixelsToPoints($wpixels);
while ($data = mysql_fetch_array($rsExport)) {
#extract($data);
$image_path = "../../../upload/jrf/".$img_upload;
$sign_path = "../../../upload/jrf/".$sign_upload;
$activeSheet->setCellValue("A".$rowNum, $i);
$activeSheet->setCellValue("B".$rowNum, $jrf_roll_no);
$activeSheet->setCellValue("C".$rowNum, $name);
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setPath($image_path);
$objDrawing->setCoordinates('D'.$rowNum);
$objDrawing->setResizeProportional(false);
$objDrawing->setWidth($wpoints);
$objDrawing->setWorksheet($activeSheet);
$activeSheet->getRowDimension($rowNum)->setRowHeight($points);
$activeSheet->getColumnDimension('D'.$rowNum)->setAutoSize(true);
$objDrawing1 = new PHPExcel_Worksheet_Drawing();
$objDrawing1->setPath($sign_path);
$objDrawing1->setCoordinates('E'.$rowNum);
$objDrawing1->setResizeProportional(false);
$objDrawing1->setWidthAndHeight($wpoints,$points);
$objDrawing1->setWorksheet($activeSheet);
$activeSheet->getColumnDimension('E'.$rowNum)->setAutoSize(true);
$rowNum++;
$i++;
}
Related
Screen Shot of HTML Form.
Can you suggest me where am I doing mistakes in my Laravel app, each time i am uploading multiple files throug the form, files is uploading perfectly in given location, but only 1 records are being inserted into database table. Here is my code...
// Upload bg_certificateArr photo
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
initialize $ac_bg for every foreach loop.
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
$ac_bg = new AccountBankGuarantee; // like this
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
You haven't posted full code here, but I believe before loop you somehow set $ac_bg variable. So looking at your code you create one record and update it in every next loop iteration.
So to fix this you should probably do something like this:
foreach ($request->file('bg_certificate') as $key => $file) {
$ac = new Ac(); // don't know what's the exact model class here
Then in every loop iteration you will create new record instead of updating it.
So I'm trying to fetch a points table for users to add points in by garnering their total points and adding it with the installation points, however by trying to fetch their "latest" points, new users who do not have an existing row in the table will throwback an error "InvalidArgumentException; Data Missing". This would be my code below, and are there any other ways around this?
$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first();
$points['user_id'] = $input['user_id'];
$points['points_add'] = $battery['point_installation'];
$points['points_subtract'] = 0;
$points['points_total'] = $currentpoint + $battery['point_installation'];
$points['points_source_id'] = 1;
$points['created_at'] = $mytime;
$points['updated_at'] = $mytime;
$point = Points::create($points);
$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first(); of your code return an object and you are try to perform math (addition) operation on that object which is not possible. You can update your code like below.
$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first();
$points['user_id'] = $input['user_id'];
$points['points_add'] = $battery['point_installation'];
$points['points_subtract'] = 0;
if($currentpoint != null)
{
$points['points_total'] = $currentpoint->points_total + $battery['point_installation'];
}
else {
$points['points_total'] = $battery['point_installation'];
}
$points['points_source_id'] = 1;
$points['created_at'] = $mytime;
$points['updated_at'] = $mytime;
$point = Points::create($points);
This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 1 year ago.
Basically I want to make a download button for my project that will produce different csv files (one csv file per table) in memory and zip before download. It works fine but the problem is that I am only getting one row (the last result) on each mysql_fetch_array where it is supposed to return rows depending on how many are stored in the database. This code is depreciated, sorry for that.
Here is my code:
<?php
require("../includes/connection.php");
require("../includes/myLib.php");
//get the ID that is passed
$ID = $_REQUEST['q'];
$ID = xdec($ID);
//All queries to fetch data
$query = mysql_query("SELECT * FROM `ge2`.`projects` WHERE `projects`.`proj_id`='$ID'");
$query2 = mysql_query("SELECT * FROM `ge2`.`attributes` WHERE `attributes`.`proj_id`='$ID'");
$query3 = mysql_query("SELECT * FROM `ge2`.`category` WHERE `category`.`proj_id`='$ID'");
$query4 = mysql_query("SELECT * FROM `ge2`.`multipletarget` WHERE `multipletarget`.`proj_id`='$ID'");
$query5 = mysql_query("SELECT * FROM `ge2`.`data_cut` WHERE `data_cut`.`proj_id`='$ID'");
$query6 = mysql_query("SELECT * FROM `ge2`.`raw` WHERE `raw`.`proj_id`='$ID'");
//getting all array
while ($row = mysql_fetch_array($query)) {
$proj_alias = $row['proj_alias'];
$proj_id = $row['proj_id'];
$date_added = $row['date_added'];
}
while ($row1 = mysql_fetch_array($query2)) {
$attrib_param_id = $row1['param_id'];
$attrib_proj_id = $row1['proj_id'];
$attrib_cat_id = $row1['cat_id'];
$attrib_val_id = $row1['val_id'];
$attrib_name = $row1['name'];
$attrib_isCust = $row1['isCust'];
}
while ($row2 = mysql_fetch_array($query3)) {
$category_cat_id = $row2['cat_id'];
$category_name = $row2['name'];
$category_proj_id = $row2['proj_id'];
$category_desc = $row2['desc'];
}
while ($row3 = mysql_fetch_array($query4)) {
$multipletarget_id = $row3['id'];
$multipletarget_proj_id = $row3['proj_id'];
$multipletarget_mtarget1 = $row3['mtarget1'];
$multipletarget_mtarget2 = $row3['mtarget2'];
}
while ($row4 = mysql_fetch_array($query5)) {
$data_cut_id = $row4['id'];
$data_cut_proj_id = $row4['proj_id'];
$data_cut_name = $row4['name'];
$data_cut_param = $row4['param'];
$data_cut_lvl = $row4['lvl'];
$data_cut_val = $row4['val'];
}
while ($row5 = mysql_fetch_array($query6)) {
$raw_id = $row5['raw_id'];
$raw_proj_id = $row5['proj_id'];
$raw_p_id = $row5['p_id'];
$raw_url = $row5['url'];
$raw_ip = $row5['ip'];
$raw_pos = $row5['pos'];
$raw_datetaken = $row5['datetaken'];
$raw_used = $row5['used'];
$raw_fdc_id = $row5['fdc_id'];
$raw_dq = $row5['dq'];
}
// some data to be used in the csv files
$records = array(
$proj_alias, $proj_id, $date_added
);
$records2 = array(
$attrib_param_id, $attrib_proj_id, $attrib_cat_id, $attrib_val_id, $attrib_name, $attrib_isCust
);
$records3 = array(
$category_cat_id, $category_name, $category_proj_id, $category_desc
);
$records4 = array(
$multipletarget_id, $multipletarget_proj_id, $multipletarget_mtarget1, $multipletarget_mtarget2
);
$records5 = array(
$data_cut_id, $data_cut_proj_id, $data_cut_name, $data_cut_param,$data_cut_lvl,$data_cut_val
);
$records6 = array(
$raw_id, $raw_proj_id, $raw_p_id, $raw_url,$raw_ip,$raw_pos,$raw_datetaken,$raw_used,$raw_fdc_id,$raw_dq
);
//making an array to be used in loop
$set = array($records,$records2,$records3,$records4,$records5,$records6);
//names to be named for each csv file
$names = array('projects', 'attributes', 'category', 'multipletarget', 'data_cut', 'raw');
// create zip file
$zipname = $proj_alias;
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
// loop to create csv files
$n = 0;
foreach ($set as $setk => $sets) {
$n += 1;
$fd = fopen('php://temp/maxmemory:1048576', 'w');
if (false === $fd) {
die('Failed to create temporary file');
}
fputcsv($fd, $sets);
// return to the start of the stream
rewind($fd);
// add the in-memory file to the archive, giving a name
$zip->addFromString('BrainLink-' . $proj_alias . "-" . $names[$setk] . '.csv', stream_get_contents($fd));
//close the file
fclose($fd);
}
// close the archive
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname.'.zip');
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
// remove the zip archive
// you could also use the temp file method above for this.
unlink($zipname);
?>
Thanks in advance.
Well, it seems that you're independently iterating over all query results and overwriting the variables over and over again. So in the end, you have only last table results to work with.
You might try using JOIN OR UNION SELECT in MySQL to get all the items in one big query result row:
$query = mysql_query('SELECT proj.*, attrs.*
FROM `projects` AS proj
JOIN `attributes` AS attrs ON (attrs.project_id=proj.project_id)
<..more tables to join in the same manner..>
WHERE proj.`proj_id`= ' . $projectId);
And then, you'll just have to iterate only over a single query resource.
while ($row = mysql_fetch_array($query)) {
//your code here
}
Note, that if tables being JOIN'ed have the same column names, they will "overwrite" each other and you'll have to rename them yourself "on the fly".
Like so:
SELECT proj.field, proj.another_field, proj.conflicting_field_name AS unique_field_name
I did not read all of your code, but in each while loop, you only save last record. It should be something like this.
while($row = mysql_fetch_array($query)){
$proj_alias[] = $row['proj_alias'];
$proj_id[] = $row['proj_id'];
$date_added[] = $row['date_added'];
}
and the others like above.
I am using following script to upload images. Here is the link : http://filer.grandesign.md/
Using this script It's allowing the preview after upload the image. Like bellow image :
You can see that, it's also allowing to delete the Image - See red bucket icon
What I am doing now :
When I upload the image I renamed the uploaded image and save it to database.
The code is bellow :
require_once('class.upload.php');
if(!isset($_FILES['files'])) {
die();
}
$files = array();
foreach ($_FILES['files'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new upload($file);
if ($handle->uploaded) {
$handle->file_new_name_body = 'mpic_list_'.uniqid('', true);
$menu_list_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 360;
$handle->image_y = 240;
$handle->process('images/menu_images/');
$handle->file_new_name_body = 'mpic_small_'.uniqid('', true);
$menu_small_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 100;
$handle->image_y = 65;
$handle->process('images/menu_images/');
$handle->file_new_name_body = 'mpic_large_'.uniqid('', true);
$menu_large_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 700;
$handle->image_y = 470;
$handle->process('images/menu_images/');
if ($handle->processed) {
$all_images = $menu_list_image . $menu_small_image . $menu_large_image;
$u_id = (int) $_SESSION['logged_user_id'];
if(!isset($_SESSION['last_id'])) {
// insert upload image section data...
$insert_menu_details = mysqli_query($conn, "INSERT INTO products (p_id) VALUES ('')");
$last_id = mysqli_insert_id($conn);
$insert_upload_image = mysqli_query($conn, "INSERT INTO product_images VALUES ('', '$menu_large_image', '$menu_list_image', '$menu_small_image', '$last_id', '$u_id')");
$_SESSION['last_id'] = $last_id;
} else {
// update upload image section data
$session_last_id = $_SESSION['last_id'];
$update_upload_image = mysqli_query($conn, "INSERT INTO product_images VALUES ('', '$menu_large_image', '$menu_list_image', '$menu_small_image', '$session_last_id', '$u_id')");
}
$handle->clean();
} else {
//echo 'error : ' . $handle->error;
echo 'Error';
}
}
}
What I need :
Now I want to delete my uploaded image. But here is an issue which is : by default this script is deleting the uploaded image using following PHP line :
<?php
if(isset($_POST['file'])){
$file = 'images/menu_images/' . $_POST['file'];
if(file_exists($file)){
unlink($file);
}
}
?>
But I can't delete it because when I upload the image to folder (images/menu_images/) I renamed it to something like that : abedkd12415775554.jpg
My Question is How can I delete my uploaded image using this script ?
You need to return the new images name that you are generating from server scripting like-
In the loop you are executing for inserting filename in database-
$array = array("oldName" => "newName");
echo json_encode($array);
You can also use numeric index if you are using some logic at your javascript end for creating array.
In javascript on delete option you can retrieve the value by using the image name and can perform delete.
check this
$res=mysqli_query("SELECT file FROM tbl_uploads WHERE id=".$_GET['remove_id']);
$row=mysqli_fetch_array($res);
mysqli_query("DELETE FROM tbl_uploads WHERE id=".$_GET['remove_id']);
unlink("uploads/".$row['file']);
Replace Your table and id name
Im having a excel sheet with the format 10/12/2012.then i convert it into csv file i have a date as "41253",When i import that into my database it is storing as 0000-00-00. How to convert the date format while importing. or is there any other way?.
This is the code im using to import to database
if(isset($_POST['Submit']))
{
GLOBAL $HTTP_POST_FILES;
//$path= $HTTP_POST_FILES['ufile']['name'];
$path= $_FILES['ufile']['name'];
//
if(copy($_FILES['ufile']['tmp_name'], $path))
{
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="xyz"; // Database name
$tbl_name="productsegmentmaster"; // Table name
require_once '.\phpExcelReader\Excel\reader.php';
$excel = new Spreadsheet_Excel_Reader();
$excel->setOutputEncoding('CP1251');
$excel->read($path);
$x=2;
$sep = "*";
ob_start();
while($x<=$excel->sheets[0]['numRows']) {
$y=1;
$row="";
while($y<=$excel->sheets[0]['numCols']) {
$cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
$row.=($row=="")?"".$cell."":"".$sep."".$cell."";
$y++;
}
echo $row."\n";
$x++;
}
//echo "Sheet count:$x";
$fp = fopen("data.csv",'w');
fwrite($fp,ob_get_contents());
fclose($fp);
//echo"----";
ob_end_clean();
//connect to the database
$connect = mysql_connect("localhost","root","");
mysql_select_db("AmaraRaja",$connect); //select the table
//$file = $_FILES['data.csv']['tmp_name'];
$handle = fopen('data.csv',"r");
//loop through the csv file and insert into database
global $data;
do {
//echo "$data[0]";
//echo "$data[1]";
//echo "$data[2]";
//$post['ProductSegmentCode'] = $data[0];
// $post['ProductSegment'] = $data[1];
// $post['ProductGroup'] = $data[2];
$post['ProductCode'] = $data[0];
$post['WarrantyPeriod'] = $data[1];
$post['ProRataPeriod'] = $data[2];
$test = date("Y-m-d",strtotime($data[3]));
$post['ManufactureDate'] = $test;
$test1 = date("Y-m-d",strtotime($data[4]));
echo $data[4];
$post['ApplicableFormDate'] = $test1;
$tname = "productwarranty";
try
{
if($data[0]!="")
{
$news->addNews($post,$tname);
//mysql_query("INSERT INTO productsegmentmaster VALUES ( '$data[0]', '$data[1]','$data[2]')");
}
}
catch(Exception $e)
{
echo $e.getMessage();
}
} while ($data = fgetcsv($handle,1000,"*","'"));
echo"<script>alert('File $path Imported Successfully')</script>";
}
fclose($handle);
unlink('data.csv');
unlink($path);
}
?>
Sadly, I have the same exact problem! I tried the format way, didn't work!
I don't know if it's applicable to you, but a solution that I came with was put a apostrophe in front of it! ('YYYY/mm/dd). The Excel itself omit the apostrophe and only show data AS TEXT, not as a Excel timestamp. In that way you can explode the data by "/" and put it in the way you want.
BUT, if is impossible to you put a apostrophe in front in every one of them, you can verifiy if is a number and try to convert the excel timestamp to unix timestamp, assuming you server a *NIX like.
=)
I know it isn't the best solution, but so far is what I can get. Hope it helps you.
Try This
$date_format = floor($excelDateTime);
$time_format = $excelDateTime - $date_format;
$mysql_strdate = ($date_format > 0) ? ( $date_format - 25569 ) * 86400 + $time_format * 86400 : $time_format * 86400;
$mysql_date_format = date("Y-d-m", $mysql_strdate);