I need to write data from MySQL table to PDF file and download using PHP and MySQL. For this I am using FPDF to create PDF file but in my case its not working as expected and throwing the below error.
Error:
<b>Warning</b>: file_put_contents(report_22-05-2019 18:36:24.pdf): failed to open stream: Permission denied in <b>/var/www/hlwcab.com/public_html/cab/include/libs/fpdf.php</b> on line <b>1021</b><br />
<br />
<b>Fatal error</b>: Uncaught exception 'Exception' with message 'FPDF error: Unable to create output file: report_22-05-2019 18:36:24.pdf'
I am providing my code below.
require_once '../../../include/libs/fpdf.php';
class PDF extends FPDF{
// Page header
function Header(){
// Logo
$this->Image('../../../admin/img/HLW-CabManagementLogo.png',10,-1,70);
$this->SetFont('Arial','B',13);
// Move to the right
$this->Cell(80);
// Title
$this->Cell(80,10,'Report List',1,0,'C');
// Line break
$this->Ln(20);
}
// Page footer
function Footer(){
// Position at 1.5 cm from bottom
$this->SetY(-15);
// Arial italic 8
$this->SetFont('Arial','I',8);
// Page number
$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
}
}
if ($_REQUEST["action"]=="downloadMonthlyReportData") {
$data=array();
$start_time=$_POST['start_time'];
$end_time=$_POST['end_time'];
$sql="select * from cb_wallet_driver_logs order by id desc";
$stmt = $db->prepare($sql);
if ($stmt->execute()) {
$row = $stmt->fetchAll();
$number_of_rows= count($row);
if ($number_of_rows > 0) {
$slno=1;
foreach ($row as $key => $value) {
$last_update=$value['last_update'];
$owner_id=$value['owner_id'];
$sql="select * from cb_owner_info where owner_id=:owner_id";
$stmt = $db->prepare($sql);
$stmt->bindParam(':owner_id', htmlspecialchars(strip_tags($owner_id)));
if ($stmt->execute()) {
$orow = $stmt->fetchAll();
$number_of_orows= count($orow);
if ($number_of_orows > 0) {
foreach ($orow as $key => $val) {
$owner_name=$val['name'];
}
}
}
$dt = new DateTime($last_update);
$odate=$dt->format('d-m-Y');
$ndate=date('d-m-Y',strtotime($odate));
$stdate=date('d-m-Y',strtotime($start_time));
$endate=date('d-m-Y',strtotime($end_time));
if ($ndate >= $stdate && $ndate <= $endate) {
$data[]=array("sl_no"=>$slno,"owner_name"=>$owner_name,"last_update"=>$last_update,"book_id"=>$value['book_id'],"operator_total"=>$value['operator_total'],"ride_total"=>$value['ride_total']);
}
$slno++;
}
}
}
$result1=array();
if (count($data) > 0) {
$pdf = new PDF();
//header
$pdf->AddPage();
//foter page
$pdf->AliasNbPages();
$pdf->SetFont('Arial','B',12);
$column[]=array("Sl No","Owner name","Date","Booking ID","Operator Total","Ride Total");
//print_r($column);exit;
foreach ($column as $key => $value) {
$pdf->Cell(40,12,$value,1);
}
foreach ($data as $key => $value) {
$pdf->Ln();
foreach ($value as $column) {
$pdf->Cell(40,12,$column,1);
}
}
$today=date('d-m-Y H:i:s');
$filename='report_'.$today.'.pdf';
$pdf->Output($filename, "F");
$result1["msg"] = "Succesfully Downloaded...";
}else{
header("HTTP/1.0 401 Unauthorized");
$result1["msg"] = "No record to download...";
}
//print_r($result1);exit;
echo json_encode($result1);
}
Here I am fetching the data from MySQL which is happening and writing those data into PDF file. Also as per error I set the 777 permission but still those errors are coming. Here I need to create the PDF file and download it in the browser.
Related
I am facing one issue while producing PDF file using PHP and FPDF. My code is below:
require_once('/var/www/hlwcab.com/public_html/cab/service/sms/smsAPIService.php');
class PDF extends FPDF{
// Page header
function Header(){
// Logo
$this->Image('../../../admin/img/HLW-CabManagementLogopdf.png',10,-1,30);
$this->SetFont('Arial','B',13);
// Move to the right
$this->Cell(80);
// Title
$this->Cell(80,10,'Report List',1,0,'C');
// Line break
$this->Ln(20);
}
// Page footer
function Footer(){
// Position at 1.5 cm from bottom
$this->SetY(-15);
// Arial italic 8
$this->SetFont('Arial','I',8);
// Page number
$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
}
}
if ($_REQUEST["action"]=="downloadMonthlyReportData") {
$data=array();
$start_time=$_POST['start_time'];
$end_time=$_POST['end_time'];
$sql="select * from cb_wallet_driver_logs order by id desc";
$stmt = $db->prepare($sql);
if ($stmt->execute()) {
$row = $stmt->fetchAll();
$number_of_rows= count($row);
if ($number_of_rows > 0) {
$slno=1;
foreach ($row as $key => $value) {
$last_update=$value['last_update'];
$owner_id=$value['owner_id'];
$sql="select * from cb_owner_info where owner_id=:owner_id";
$stmt = $db->prepare($sql);
$stmt->bindParam(':owner_id', htmlspecialchars(strip_tags($owner_id)));
if ($stmt->execute()) {
$orow = $stmt->fetchAll();
$number_of_orows= count($orow);
if ($number_of_orows > 0) {
foreach ($orow as $key => $val) {
$owner_name=$val['name'];
}
}
}
$dt = new DateTime($last_update);
$odate=$dt->format('d-m-Y');
$ndate=date('d-m-Y',strtotime($odate));
$stdate=date('d-m-Y',strtotime($start_time));
$endate=date('d-m-Y',strtotime($end_time));
if ($ndate >= $stdate && $ndate <= $endate) {
$data[]=array("sl_no"=>$slno,"owner_name"=>$owner_name,"last_update"=>$last_update,"book_id"=>$value['book_id'],"operator_total"=>$value['operator_total'],"ride_total"=>$value['ride_total']);
$slno++;
}
}
}
}
$result1=array();
if (count($data) > 0) {
$pdf = new PDF();
//$pdf = new FPDF();
//header
$pdf->AddPage();
$width_cell=array(10,30,40,40,30,30);
$pdf->SetFont('Arial','B',12);
$pdf->SetFillColor(193,229,252);
$pdf->Cell($width_cell[0],10,'Sl No',1,0,C,true);
$pdf->Cell($width_cell[1],10,'Owner Name',1,0,C,true);
$pdf->Cell($width_cell[2],10,'Date',1,0,C,true);
$pdf->Cell($width_cell[3],10,'Booking ID',1,0,C,true);
$pdf->Cell($width_cell[4],10,'Operator',1,1,C,true);
$pdf->Cell($width_cell[5],10,'Ride',1,1,C,true);
$pdf->SetFont('Arial','',10);
//Background color of header//
$pdf->SetFillColor(235,236,236);
//to give alternate background fill color to rows//
$fill=false;
foreach ($data as $row) {
$pdf->Cell($width_cell[0],10,$row['sl_no'],1,0,C,$fill);
$pdf->Cell($width_cell[1],10,$row['owner_name'],1,0,L,$fill);
$pdf->Cell($width_cell[2],10,$row['last_update'],1,0,C,$fill);
$pdf->Cell($width_cell[3],10,$row['book_id'],1,0,C,$fill);
$pdf->Cell($width_cell[4],10,$row['operator_total'],1,1,C,$fill);
$pdf->Cell($width_cell[5],10,$row['ride_total'],1,1,C,$fill);
$fill = !$fill;
}
$today = date('YmdHi');
$filename='report_'.$today.'.pdf';
$totalpath='/var/www/hlwcab.com/public_html/cab/service/admin/report/download/'.$filename;
$pdf->Output($totalpath, "F");
$result1["msg"] = "Succesfully Downloaded...";
}else{
header("HTTP/1.0 401 Unauthorized");
$result1["msg"] = "No record to download...";
}
//print_r($result1);exit;
echo json_encode($result1);
}
Here I am first fetching the data from MySQL table and creating the pdf file which is given below.
Here the last header column is breaking and coming to down. Here I need to set all header part of column in the same row.
Change the 2nd one (1) in the line below to zero (0).
From:
pdf->Cell($width_cell[4],10,'Operator',1,1,C,true);
To:
pdf->Cell($width_cell[4],10,'Operator',1,0,C,true);
Do the same for the cell in the loop that outputs the actual values. From:
pdf->Cell($width_cell[4],10,$row['operator_total'],1,1,C,$fill);
To:
pdf->Cell($width_cell[4],10,$row['operator_total'],1,0,C,$fill);
I want to change the font color of the text in PDF to absent is to red and present is to green. How can i add those in these codes? Need help for a beginner. Thanks alot.
Btw, I used fpdf to make the output a downloadable pdf.
<?php
//include connection file
include "db.php";
include_once('fpdf.php');
class PDF extends FPDF
{
// Page header
function Header()
{
// Logo
// $this->Image('https://i2.wp.com/tutorialswebsite.com/wp-content/uploads/2016/01/cropped-LOGO-1.png',10,10,50);
$this->SetFont('Arial','B',13);
// Move to the right
$this->Cell(80);
// Title
$this->Cell(80,10,'ICT-5 Attendance',1,0,'C');
// Line break
$this->Ln(20);
}
// Page footer
function Footer()
{
// Position at 1.5 cm from bottom
$this->SetY(-15);
// Arial italic 8
$this->SetFont('Arial','I',8);
// Page number
$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
}
}
Should i add that in here?
$display_heading = array('roll_number'=>'Roll Number', 'student_name'=> 'Name of Student', 'attendance_status'=> 'Attendance Status','id'=> 'DATABASE ID Num.','date'=> 'Date');
$result = mysqli_query($conn, "SELECT id, student_name, roll_number, attendance_status, date FROM attendance_records WHERE date ='$_POST[date]'") or die("database error:". mysqli_error($conn));
$header = mysqli_query($conn, "SHOW columns FROM attendance_records WHERE field != 'created_on'");
$pdf = new PDF();
//header
$pdf->AddPage();
//foter page
$pdf->AliasNbPages();
$pdf->SetFont('Arial','B',10);
foreach($header as $heading) {
$pdf->Cell(39,10,$display_heading[$heading['Field']],1);
}
foreach($result as $row) {
$pdf->SetFont('Arial','I',8.5);
$pdf->Ln();
foreach($row as $column)
$pdf->Cell(39,10,$column,1);
}
$pdf->Output();
?>
I'm not sure about this but perhaps it will help. I've never used fPDF but a quick look at the documentation suggests that SetTextColor would be the method you need.
foreach( $result as $row ) {
$pdf->SetFont('Arial','I',8.5);
$pdf->Ln();
foreach($row as $column) {
switch( $row['attendance_status'] ){
case 'Absent': $pdf->SetTextColor(255,0,0); break;
case 'Present':$pdf->SetTextColor(0,255,0);break;
}
$pdf->Cell(39,10,$column,1);
}
}
To change ( hopefully ) just the word Absent/Present try this perhaps:
foreach( $result as $row ) {
$pdf->SetFont('Arial','I',8.5);
$pdf->Ln();
foreach($row as $fieldname => $column) {
if( $fieldname=='attendance_status' ){
switch( $row['attendance_status'] ){
case 'Absent': $pdf->SetTextColor(255,0,0); break;
case 'Present':$pdf->SetTextColor(0,255,0);break;
}
} else {
$pdf->SetTextColor(0,0,0); #default to BLACK
}
$pdf->Cell(39,10,$column,1);
}
}
I am trying to import data via excel sheet into database with codeigniter application.I am using phpexcel. However the code is right but i am getting an error which states:
Error Number: 1054
Unknown column 'joker' in 'field list'
INSERT INTO studentsaccount (joker) VALUES ('')
Filename: C:/xampp/htdocs/Nalanda_Library/system/database/DB_driver.php
Line Number: 691
however my code is as follows: for controller
public function studentaccountimport(){
$this->load->model('Department');
$file = $_FILES['upload']['tmp_name'];
//load the excel library
$this->load->library('excel');
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file);
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
$this->Department->modeluploadation($data_value);
}
}
}
for model:
public function modeluploadation($data){
$this->db->insert('studentsaccount',$data);
}
i am novice in codeigniter here so please help
You need to specify column names in insert query..
try
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
$data['header'] = $header;
$data['values'] = $arr_data;
$this->Department->modeluploadation($data);
Ok the reason for your problem is you need to pass an array of key=>value pairs as the parameter for insert().
I'm not sure why Safins answer has been marked down because he is right. So when you should set modeluploadation as:
public function modeluploadation($data){
$this->db->insert('studentsaccount',array('field_name'=>$data_value));
}
I have succeeded in outputting a pdf and the width of the email and address column is overlapping into the next column. I need help on how to make it print the results from the database in a new line even though the word length is longer than the column width, it should just break and extend the height of the entire row.
Below is my code;
<?php
require('fpdf.php');
$db = new PDO('mysql:host=localhost;dbname=ddname;charset=utf8', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$colNames = array();
$result = $db->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='dbname' AND TABLE_NAME='table_name'");
foreach($result as $row) {
$colNames[] = $row["COLUMN_NAME"];
}
$pdf = new FPDF('L','mm','A4');
$pdf->AddPage();
$pdf->SetDisplayMode(real,'default');
$pdf->SetFont('Arial','B',12);
$pdf->SetTextColor(50,60,100);
$pdf->SetDrawColor(50,60,100);
$pdf->Cell(100,10,'Tabledata table_name',1,0,'C',0);
$pdf->Ln();
foreach($colNames as $colName) {
$pdf->SetFont('Arial','B',8);
if($colName=="id")
{
$pdf->Cell(6,10,$colName,1);
} elseif($colName=="email_address"){
$pdf->Cell(22,10,$colName,1);}elseif($colName=="title"){
$pdf->Cell(10,10,$colName,1);}else
{
$pdf->Cell(22,10,$colName,1);
}
}
foreach($db->query("SELECT * FROM table_name") as $row2) {
$pdf->Ln();
foreach($colNames as $colName) {
$pdf->SetFont('Arial','',8);
if($colName=="id")
{
$pdf->Cell(6,10,$row2[$colName],1);
} elseif($colName=="title"){
$pdf->Cell(10,10,$row2[$colName],1);}else
{
$pdf->Cell(22,10,$row2[$colName],1);
}
}
}
$pdf->Output();
?>
This is a sample of the current result
Am a trying to create a PHP (PHrets) script that downloads all real estate listing information from a specific area and saves all of the listings data (CSV file and photos) on my web server.
Note: A single listing may have up to 20 photos.
I am using PHrets to retrieve MLS listing data and it works great for creating a CSV of data. However, I would like to modify this code to loop through each listing's photos and download them onto my web server with the following name convention: MLSID-PHOTOID.
The error below is coming from the GetObject loop at the end of the code:
ERROR Message: HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.
Thanks in advance!
<?php
$rets_login_url = "http://maxebrdi.rets.fnismls.com/Rets/FNISRETS.aspx/MAXEBRDI/login?&rets-version=rets/1.5";
$rets_username = "MyUser";
$rets_password = "MyPass";
// use http://retsmd.com to help determine the SystemName of the DateTime field which
// designates when a record was last modified
$rets_status_field = "L_StatusCatID";
$rets_city_field = "L_City";
// use http://retsmd.com to help determine the names of the classes you want to pull.
// these might be something like RE_1, RES, RESI, 1, etc.
//"RE_1"
$property_classes = array("LR_5");
// DateTime which is used to determine how far back to retrieve records.
// using a really old date so we can get everything
$listing_status = 1;
$listing_city = "OAKLAND";
//////////////////////////////
require_once("phrets.php");
// start rets connection
$rets = new phRETS;
echo "+ Connecting to {$rets_login_url} as {$rets_username}<br>\n";
$connect = $rets->Connect($rets_login_url, $rets_username, $rets_password);
if ($connect) {
echo " + Connected<br>\n";
}
else {
echo " + Not connected:<br>\n";
print_r($rets->Error());
exit;
}
foreach ($property_classes as $class) {
echo "+ Property:{$class}<br>\n";
$file_name = strtolower("property_{$class}.csv");
$fh = fopen($file_name, "w+");
$maxrows = true;
$offset = 1;
$limit = 1000;
$fields_order = array();
while ($maxrows) {
$query = "({$rets_status_field}={$listing_status}),({$rets_city_field}={$listing_city})";
// run RETS search
echo " + Query: {$query} Limit: {$limit} Offset: {$offset}<br>\n";
$search = $rets->SearchQuery("Property", $class, $query, array("Limit" => $limit, "Offset" => $offset, "Format" => "COMPACT", "Select" => "L_ListingID,L_Class,L_Type_,L_Status,L_AskingPrice,L_Keyword2,L_Keyword3,L_Keyword4,L_SquareFeet,L_Remarks,L_Address,L_City,L_State,LO1_OrganizationName,LA1_AgentLicenseID,LA1_UserFirstName,LA1_UserLastName,L_PictureCount", "Count" => 1));
if ($rets->NumRows() > 0) {
if ($offset == 1) {
// print filename headers as first line
$fields_order = $rets->SearchGetFields($search);
fputcsv($fh, $fields_order);
}
// process results
while ($record = $rets->FetchRow($search)) {
$this_record = array();
foreach ($fields_order as $fo) {
$this_record[] = $record[$fo];
}
fputcsv($fh, $this_record);
}
$offset = ($offset + $rets->NumRows());
}
$maxrows = $rets->IsMaxrowsReached();
echo " + Total found: {$rets->TotalRecordsFound()}<br>\n";
$rets->FreeResult($search);
}
fclose($fh);
echo " - done<br>\n";
}
/*
//This code needs to be fixed. Not sure how to include the listing array correctly.
$photos = $rets->GetObject("Property", "Photo", $record[ListingID], "*", 1);
foreach ($photos as $photo) {
$listing = $photo['Content-ID'];
$number = $photo['Object-ID'];
if ($photo['Success'] == true) {
echo "{$listing}'s #{$number} photo is at {$photo['Location']}\n";
file_put_contents("photos/{$photo['Content-ID']}-{$photo['Object-ID']}.jpg",
$photo['Data']);
}
else {
echo "Error ({$photo['Content-ID']}-{$photo['Object-ID']}
}
}
//ERROR Message: HTTP Error 500 (Internal Server Error): An unexpected condition was //encountered while the server was attempting to fulfill the request.
*/
echo "+ Disconnecting<br>\n";
$rets->Disconnect();
I modified your while loop that processes each record to also get the photos for that record. I also tested this on a RETS server.
while ($record = $rets->FetchRow($search)) {
$this_record = array();
foreach ($fields_order as $fo) {
if ($fo == 'L_ListingID') {
$photos = $rets->GetObject("Property", "Photo", $record[$fo], "*", 1);
foreach ($photos as $photo) {
if ($photo['Success'] == true) {
file_put_contents("photos/{$photo['Content-ID']}-{$photo['Object-ID']}.jpg", $photo['Data']);
}
}
}
$this_record[] = $record[$fo];
}
fputcsv($fh, $this_record);
}
One thing I found is you have ListingID on this line:
$photos = $rets->GetObject("Property", "Photo", $record[ListingID], "*", 1);
But then in your search query you refer to ListingID as L_ListingID. Maybe the above line should have L_ListingID.
$search = $rets->SearchQuery("Property", $class, $query, array("Limit" => $limit, "Offset" => $offset, "Format" => "COMPACT", "Select" => "L_ListingID,L_Class,L_Type_,L_Status,L_AskingPrice,L_Keyword2,L_Keyword3,L_Keyword4,L_SquareFeet,L_Remarks,L_Address,L_City,L_State,LO1_OrganizationName,LA1_AgentLicenseID,LA1_UserFirstName,LA1_UserLastName,L_PictureCount", "Count" => 1));
What if the last parameter of GetObject is "0" :
$photos = $rets->GetObject("Property", "Photo", $record[$fo], "*", 1);
in this case "1" is for retreiving the location. some servers this is switched off and return the actual image I believe - that would require a different method.