Showing unknown characters when excel forced to download in PhpExcel codeigniter - php

I am using PhpExcel to download reports as excel in my codeigniter application. When I try to download my report its showing some characters on the browser instead of downloading the file. This has worked fine in localhost but not working in the server. I dont know whats the problem. Here is my code:
View
<div class="box-content">
<div class="row">
<div class="col-lg-12">
<p class="introtext"><?= lang('customize_report'); ?></p>
<div id="form">
<?php echo form_open("reports/getSalesaccReport"); ?>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label class="control-label" for="reference_no"><?= lang("reference_no"); ?></label>
<?php echo form_input('reference_no', (isset($_POST['reference_no']) ? $_POST['reference_no'] : ""), 'class="form-control tip" id="reference_no"'); ?>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="control-label" for="user"><?= lang("created_by"); ?></label>
<?php
$us[""] = "";
foreach ($users as $user) {
$us[$user->id] = $user->first_name . " " . $user->last_name;
}
echo form_dropdown('user', $us, (isset($_POST['user']) ? $_POST['user'] : ""), 'class="form-control" id="user" data-placeholder="' . $this->lang->line("select") . " " . $this->lang->line("user") . '"');
?>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="control-label" for="customer"><?= lang("customer"); ?></label>
<?php echo form_input('customer', (isset($_POST['customer']) ? $_POST['customer'] : ""), 'class="form-control" id="customer" data-placeholder="' . $this->lang->line("select") . " " . $this->lang->line("customer") . '"'); ?>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="control-label" for="biller"><?= lang("biller"); ?></label>
<?php
$bl[""] = "";
foreach ($billers as $biller) {
$bl[$biller->id] = $biller->company != '-' ? $biller->company : $biller->name;
}
echo form_dropdown('biller', $bl, (isset($_POST['biller']) ? $_POST['biller'] : ""), 'class="form-control" id="biller" data-placeholder="' . $this->lang->line("select") . " " . $this->lang->line("biller") . '"');
?>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="control-label" for="warehouse"><?= lang("warehouse"); ?></label>
<?php
$wh[""] = "";
foreach ($warehouses as $warehouse) {
$wh[$warehouse->id] = $warehouse->name;
}
echo form_dropdown('warehouse', $wh, (isset($_POST['warehouse']) ? $_POST['warehouse'] : ""), 'class="form-control" id="warehouse" data-placeholder="' . $this->lang->line("select") . " " . $this->lang->line("warehouse") . '"');
?>
</div>
</div>
<?php if($this->Settings->product_serial) { ?>
<div class="col-sm-4">
<div class="form-group">
<?= lang('serial_no', 'serial'); ?>
<?= form_input('serial', '', 'class="form-control tip" id="serial"'); ?>
</div>
</div>
<?php } ?>
<div class="col-sm-4">
<div class="form-group">
<?= lang("start_date", "start_date"); ?>
<?php echo form_input('start_date', (isset($_POST['start_date']) ? $_POST['start_date'] : ""), 'class="form-control datetime" id="start_date"'); ?>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<?= lang("end_date", "end_date"); ?>
<?php echo form_input('end_date', (isset($_POST['end_date']) ? $_POST['end_date'] : ""), 'class="form-control datetime" id="end_date"'); ?>
</div>
</div>
</div>
<div class="form-group">
<div
class="controls"> <?php echo form_submit('submit_report', $this->lang->line("submit"), 'class="btn btn-primary"'); ?> </div>
</div>
<?php echo form_close(); ?>
</div>
Controller
function getSalesaccReport()
{
if ($this->input->post('customer')) {
$customerid = $this->input->post('customer');
} else {
$customerid = NULL;
}
echo $customerid;
if ($this->input->post('biller')) {
$biller = $this->input->post('biller');
} else {
$biller = NULL;
}
if ($this->input->post('warehouse')) {
$warehouse = $this->input->post('warehouse');
} else {
$warehouse = NULL;
}
if ($this->input->post('start_date')) {
$start_date = $this->input->post('start_date');
} else {
$start_date = NULL;
} echo $start_date;
if ($this->input->post('end_date')) {
$end_date = $this->input->post('end_date');
} else {
$end_date = NULL;
} echo $end_date;
if ($start_date) {
$start_date = $this->sma->fld($start_date);
$end_date = $this->sma->fld($end_date);
}
if (!$this->Owner && !$this->Admin) {
$user = $this->session->userdata('user_id');
}
$dateTmp = "DATE_FORMAT(".$this->db->dbprefix('sales').".date,'%m/%Y')";
$condition = "if(".$this->db->dbprefix('sales').".biller_id = 5, 'A', if(".$this->db->dbprefix('sales').".biller_id = 6, 'B',if(".$this->db-> dbprefix('sales').".biller_id = 7,'C','D' )))";
$this->db
->select("date, ".$this->db->dbprefix('warehouses').".name,
CONCAT(".$this->db->dbprefix('warehouses').".name,'-',".$dateTmp.",'-', ".$condition.",".$this->db->dbprefix('sales').".invoice_no) as month," ." biller, customer,
scan_no,unit_price,tin,cin,cst,total_discount, item_tax, shipping,subtotal,payment_status,sales.id as saleid,total_items,total,biller_id,tax_rate_id,grand_total,quantity", FALSE)
->from('sales')
->join('sale_items', 'sale_items.sale_id=sales.id', 'left')
->join('companies','companies.id=sales.customer_id', 'left')
->join('warehouses', 'warehouses.id=sales.warehouse_id', 'left')
->group_by('sales.id')
->order_by('sales.date desc');
if ($biller) {
$this->db->where('sales.biller_id', $biller);
}
if ($customerid) {
$this->db->where('sales.customer_id', $customerid);
}
if ($warehouse) {
$this->db->where('sales.warehouse_id', $warehouse);
}
if (($start_date) && ($end_date)) {
$this->db->where($this->db->dbprefix('sales').'.date BETWEEN "' . $start_date . '" and "' . $end_date . '"');
}
/* if ($start_date) {
$this->db->where($this->db->dbprefix('sales').'.date LIKE "' . $start_date . '"');
}
if ($end_date) {
$this->db->where($this->db->dbprefix('sales').'.date LIKE "' . $end_date . '"');
} */
$q = $this->db->get();
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
} else {
$data = NULL;
}
if (!empty($data))
{
$this->load->library('excel');
$this->excel->setActiveSheetIndex(0);
$this->excel->getActiveSheet()->setTitle(lang('sales_report'));
$this->excel->getActiveSheet()->SetCellValue('A1', lang('date'));
$this->excel->getActiveSheet()->SetCellValue('B1', lang('branch'));
$this->excel->getActiveSheet()->SetCellValue('C1', lang('Vch_No.'));
$this->excel->getActiveSheet()->SetCellValue('D1', lang('Voucher_Type'));
$this->excel->getActiveSheet()->SetCellValue('E1', lang('Particulars'));
$this->excel->getActiveSheet()->SetCellValue('F1', lang('TIN_No.'));
$this->excel->getActiveSheet()->SetCellValue('G1', lang('CIN'));
$this->excel->getActiveSheet()->SetCellValue('H1', lang('CST_No.'));
$this->excel->getActiveSheet()->SetCellValue('I1', lang('Scan_No'));
$this->excel->getActiveSheet()->SetCellValue('J1', lang('Product'));
$this->excel->getActiveSheet()->SetCellValue('K1', lang('quantity'));
$this->excel->getActiveSheet()->SetCellValue('L1', lang('Rate'));
$this->excel->getActiveSheet()->SetCellValue('M1', lang('Sales_#__5%'));
$this->excel->getActiveSheet()->SetCellValue('N1', lang('Output_Vat_#_5%'));
$this->excel->getActiveSheet()->SetCellValue('O1', lang('Sales_#_14.5%'));
$this->excel->getActiveSheet()->SetCellValue('P1', lang('Output_Vat_#_14.5%'));
$this->excel->getActiveSheet()->SetCellValue('Q1', lang('Sales_#_0%'));
$this->excel->getActiveSheet()->SetCellValue('R1', lang('Scanning_charge'));
$this->excel->getActiveSheet()->SetCellValue('S1', lang('Scanning_Discount'));
$this->excel->getActiveSheet()->SetCellValue('T1', lang('Shipping'));
$this->excel->getActiveSheet()->SetCellValue('U1', lang('Gross_Total'));
$row = 2;
$total = 0;
$paid = 0;
$balance = 0;
$quantity= 0;
$prdt_price = 0;
$sale5=0.00;
$output5=0.00;
$sale145=0.00;
$output145=0.00;
$sale0=0.00;
$discount=0;
foreach ($data as $data_row)
{
$saleid=$data_row->saleid;
$billerid=$data_row->biller_id;
$gross_total= $data_row->grand_total + shipping;
if($billerid==7)
{
$sale0=0;
$discount=$data_row->total_discount;
/*$scanqty=$data_row->quantity;
if($scanqty==0.5)
{
$scanning_charge+=500;
}
else if($scanqty==1)
{
$scanning_charge+=1000;
}*/
$this->db->select("sum(`quantity`*1000) as scanning_charge", FALSE);
$this->db->where('sale_id',$saleid);
$queryres = $this->db->get('sale_items');
if($queryres->num_rows() > 0)
{
foreach($queryres->result() as $queryres1)
{
$scanning_charge=$queryres1->scanning_charge;
}
}
else
{
}
}
else
{
$scanning_charge=0;
$discount=0;
}
if(($billerid==5) || ($billerid==6))
{
$this->db->select("sum( case when tax_rate_id = 1 then `net_unit_price`*`quantity` else 0 end) as sale0", FALSE);
$this->db->where('sale_id',$saleid);
$res1=$this->db->get('sale_items');
if($res1->num_rows() > 0)
{
echo $billerid;
foreach ($res1->result() as $row31)
{
$sale0=$row31->sale0;
}
}
else
{
}
}
$total0=$data_row->total;
$this->db->select("GROUP_CONCAT(DISTINCT product_name) as products,SUM(quantity)as prdtqty")
->from('sale_items')
->where('sale_id',$saleid);
$q1 = $this->db->get();
if ($q1->num_rows() > 0)
{
foreach (($q1->result()) as $row1)
{
$products = $row1->products;
$prdtqty = $row1->prdtqty;
}
}
else
{
$products="";
}
$sql="select sum( case when tax_rate_id = 2 then net_unit_price*quantity else 0 end) as sale5,
sum( case when tax_rate_id = 3 then net_unit_price*quantity else 0 end) as sale145,
sum( case when tax_rate_id = 2 then item_tax else 0 end) as output5,
sum( case when tax_rate_id = 3 then item_tax else 0 end) as output145
from sma_sale_items
where sale_id=".$saleid;
$res=$this->db->query($sql);
if($res->num_rows() > 0)
{
foreach ($res->result() as $row3)
{
$sale5=$row3->sale5;
$output5=$row3->output5;
$sale145=$row3->sale145;
$output145=$row3->output145;
}
}
$this->excel->getActiveSheet()->SetCellValue('A' . $row, $this->sma->hrld($data_row->date));
$this->excel->getActiveSheet()->SetCellValue('B' . $row, $data_row->name);
$this->excel->getActiveSheet()->SetCellValue('C' . $row, $data_row->month);
$this->excel->getActiveSheet()->SetCellValue('D' . $row, $data_row->biller);
$this->excel->getActiveSheet()->SetCellValue('E' . $row, $data_row->customer);
$this->excel->getActiveSheet()->SetCellValue('F' . $row, $data_row->tin);
$this->excel->getActiveSheet()->SetCellValue('G' . $row, $data_row->cin);
$this->excel->getActiveSheet()->SetCellValue('H' . $row, $data_row->cst);
$this->excel->getActiveSheet()->SetCellValue('I' . $row, $data_row->scan_no);
$this->excel->getActiveSheet()->SetCellValue('J' . $row, $products);
$this->excel->getActiveSheet()->SetCellValue('K' . $row, $prdtqty);
$this->excel->getActiveSheet()->SetCellValue('L' . $row, $data_row->total);
$this->excel->getActiveSheet()->SetCellValue('M' . $row, $sale5);
$this->excel->getActiveSheet()->SetCellValue('N' . $row, $output5);
$this->excel->getActiveSheet()->SetCellValue('O' . $row, $sale145);
$this->excel->getActiveSheet()->SetCellValue('P' . $row, $output145);
$this->excel->getActiveSheet()->SetCellValue('Q' . $row, $sale0);
$this->excel->getActiveSheet()->SetCellValue('R' . $row, $scanning_charge);
$this->excel->getActiveSheet()->SetCellValue('S' . $row, $discount);
$this->excel->getActiveSheet()->SetCellValue('T' . $row, $data_row->shipping);
$this->excel->getActiveSheet()->SetCellValue('U' . $row, $gross_total);
$total += $data_row->subtotal;
$paid += $data_row->item_tax;
$row++;
}
$this->excel->getActiveSheet()->getColumnDimension('A')->setWidth(18);
$this->excel->getActiveSheet()->getColumnDimension('B')->setWidth(8);
$this->excel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
$this->excel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
$this->excel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
$this->excel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
$this->excel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
$this->excel->getActiveSheet()->getColumnDimension('H')->setWidth(10);
$this->excel->getActiveSheet()->getColumnDimension('I')->setWidth(12);
$this->excel->getActiveSheet()->getColumnDimension('J')->setWidth(30);
$this->excel->getActiveSheet()->getColumnDimension('K')->setWidth(10);
$this->excel->getActiveSheet()->getColumnDimension('L')->setWidth(11);
$this->excel->getActiveSheet()->getColumnDimension('M')->setWidth(13);
$this->excel->getActiveSheet()->getColumnDimension('N')->setWidth(17);
$this->excel->getActiveSheet()->getColumnDimension('O')->setWidth(14);
$this->excel->getActiveSheet()->getColumnDimension('P')->setWidth(20);
$this->excel->getActiveSheet()->getColumnDimension('Q')->setWidth(12);
$this->excel->getActiveSheet()->getColumnDimension('R')->setWidth(18);
$this->excel->getActiveSheet()->getColumnDimension('S')->setWidth(20);
$this->excel->getActiveSheet()->getColumnDimension('T')->setWidth(12);
$this->excel->getActiveSheet()->getColumnDimension('U')->setWidth(14);
$filename = 'sales_report';
$this->excel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
$this->excel->getActiveSheet()->getStyle('E2:E' . $row)->getAlignment()->setWrapText(true);
ob_clean();
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
header('Cache-Control: max-age=0');
ob_clean();
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');
exit();
}
else{
$this->session->set_flashdata('error', lang('nothing_found'));
redirect('reports/sales_accounts');
}
}
Here is my browser view:
Can anyone please help me to fix this.. I am really in need of this.. Thanks in advance.

Try this
ob_clean();
ob_start(); # added
header('Content-type: application/vnd.ms-excel; charset=UTF-8" ); # Improved with UTF charset
header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
header('Cache-Control: max-age=0');
ob_clean(); # remove this
if you want download this with 2003 and 2007 there are few changes to be done
2007 - file format xlsx
2003 - file format xls

Related

Export list CRUD with MPDF + OB_start()

Good morning guys, developing a CRM using the CodeIgniter framework and I'm not managing to export some CRUD lists using an MPDF library.
I'm trying to use an ob_start () function as indicated in the library's own manual, but when exporting, I get the following
formatting error as a return:
error formatting
When in fact a pdf spreadsheet would return
Below, the codes used:
view:
<li><i class="fas fa-download"></i></li>
<div class="conteudo tabelaMovCaixa">
<div class="col-xs-12 usuarioTitulo">
<div class="input entrada1">
<input type="checkbox" id="checkboxAll" onclick="selecionaTodosCheckbox()" value="Selecione">
</div>
<div class="conta">
Conta
</div>
<div class="descricao">
Descrição
</div>
<div class="data">
Vencimento
</div>
<div class="tipo">
Tipo
</div>
<div class="valor">
Valor
</div>
</div>
</form>
<form action="<?php echo base_url('configuracoes/excContasCheckbox') ?>" method="POST">
<?php if ($dados_caixa_filtro == null) { ?>
<?php
$data = date('d/m/Y');
$data2 = date('d/m/Y', strtotime('-1 days', strtotime(date('Y-m-d'))));
$data3 = date('d/m/Y', strtotime('-2 days', strtotime(date('Y-m-d'))));
?>
<div class="col-xs-12 vencimento">
<h5>Vencimento: <?php echo $data ?></h5>
</div>
<?php
if (!empty($dados_caixa)) {
foreach ($dados_caixa as $dados) {
$checkbox = [];
$checkbox[] = $dados->id_contas_pagar_receber;
foreach ($checkbox as $checkbox => $value) {
//echo "ID da conta : ".$value."<br />";
}
if (date("d/m/Y", strtotime($dados->vencimento)) == $data) {
$urlExcluir = base_url('configuracoes/excContaPR') . "/" . $dados->id_contas_pagar_receber;
if ($dados->tipo_pessoa == '1') {
echo "<div class='col-xs-12 usuario saida'>";
} else if ($dados->tipo_pessoa == '2') {
echo "<div class='col-xs-12 usuario entrada'>";
}
echo "<div class='input entrada1'>"
. "<input type='checkbox' name='emp_id[]' value='$value' id='emp_id' onclick=verificarCheckBox() >"
. "</div>"
. "<div class='conta'>"
. "$dados->nome"
. "</div>"
. "<div class='descricao'>"
. $dados->descricao
. "</div>"
. "<div class='data'>";
if ($dados->vencimento == '') {
echo "----------";
} else {
echo date('d/m/Y', strtotime($dados->vencimento));
}
echo "</div>"
. "<div class='tipo'>"
. $dados->forma_pagamento
. "</div>"
. "<div class='valor'>"
. "<span class='entrada2'>" . 'R$ ' . number_format($dados->valor, 2, ',', '.') . "</span>"
. "</div>"
. "<div class='actions2'>"
. "<li><a onclick='pagar2($dados->id_contas_pagar_receber, $dados->tipo_pessoa)' title='Editar'><i class='fas fa-pencil-alt'></i></a></li>"
. "<li><a onclick='pagar($dados->id_contas_pagar_receber, $dados->tipo_pessoa)' title='Pagar'><i class='fas fa-file-invoice-dollar'></i></a></li>"
. "<li><a href='#' onclick = \"confirmExclusaoContaPR(" . '\'0' . $dados->id_contas_pagar_receber . '\',' . '\'' . $urlExcluir . '\'' . ");\" title='Excluir'><i class='fa fa-trash'></i></a></li>"
. "</div>"
. "</div>";
for ($i = 0; $i < count(['checkbox']); $i++) {
$id = $value;
//echo $value;
}
}
}
}
?>
I am placing the ob_start () function right at the beginning of the view containing the HTML of the page.
Controler:
function gerarPdfRelatorio()
{
if ($this->session->userdata('logado') == true) {
date_default_timezone_set('America/Fortaleza');
setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
date_default_timezone_set('America/Sao_Paulo');
$dadosC['dados_caixa'] = $this->financeiro->retornaListaMovimentacaoCaixa();
$dadosC['dados_caixa_filtro'] = null;
if ($this->session->userdata('tipo_filtro_movcaixa')) {
$this->session->unset_userdata("tipo_filtro_movcaixa");
}
$this->load->view('admin/head');
$dadosC['lista_cliente'] = $this->relatorio->buscaClienteFornecedor();
$dadosC['lista_centro_custo'] = $this->financeiro->listaCentroCusto();
$this->load->view('admin/head');
$this->load->view('admin/relatorio', $dadosC);
} else {
$dados['mensagem'] = null;
$dados['mensagem_tipo'] = 'error';
$this->paginas($dados);
}
}
This is where I generate the PDF:
<?php
set_time_limit(0);
include_once __DIR__ . '/../../../vendor/autoload.php';
$mpdf = new \Mpdf\Mpdf();
$mpdf->debug = true;
$conteudoPDF = $this->load->view('admin/relatorios/relatorio_geral.php', '', true);
$header = '<div><img src="assets/img/logo_contrato2.jpeg" width="800"></div>';
$conteudoPDF = mb_convert_encoding($conteudoPDF, 'UTF-8', 'UTF-8');
$mpdf->WriteHTML($conteudoPDF);
ob_clean();
$mpdf->WriteHTML($conteudoPDF, 0);
ob_clean();
$mpdf->Output();
This is the list I'm trying to generate
tabela
I would like to know how I can format this data to appear in spreadsheet format in pdf

files wont upload to server

Hi I am having trouble uploading files to my server, they enter the database fine and the path is correct but for some reason the files just wont go in.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach ($_FILES['ppt']['name'] AS $name) {
$i = 1;
$ppt = strtolower(str_replace(' ', '_', $name.$i));
$pathinfo = pathinfo($name, PATHINFO_EXTENSION);
$data = array(
'eid' => $_GET['id'],
'ppt_filename' => $name.$i,
'ppt_extension' => $pathinfo
);
$db::table('ppts')
->insert($data);
if ($_FILES['ppt']['tmp_name']) {
try {
move_uploaded_file($_FILES['ppt']['tmp_name'], DOCROOT . '/_data/ppt/' . $name . '.' . $pathinfo);
} catch (Exception $e) {
echo 'broken';
exit;
}
$i++;
}
}
}
This is the PHP im using to handle the post.
<div class="card bg-grey">
<h4 class="card-header bg-blue text-white text-bold">Uploads</h4>
<div class="card-block">
<div id="<?php echo $field_name; ?>" class="form-group <?php echo $_ERROR[$field_name] ? ' has-danger' : ''; ?>">
<input <?php echo ($_SESSION['level'] == 1 || $event->created_by == $_SESSION['id'] ? '' : 'readonly="readonly"'); ?> type="file" name="ppt[]" class="form-control" placeholder=""/>
<label>Powerpoint</label>
</div>
</div>
</div>
This is the HTML where I am submitting the file

Codeigniter calendar not displaying correct data and set limit not working

I am using CodeIgniter Calendar library.
I have two tables that I get calendar data from my database.
events table
extra_events table
The problem I have 2 foreach loops with the second foreach loop $query2->result_array() it does not let me get the first events on each day from database table extra_events I am also trying to be able to set the limit from the extra events table but not working.
From the extra_events table
Example
Test 2 | Example 2
| Example 3
It should produce
Test 1 | Example 1 <!-- Missing
Test 2 | Example 2
| Example 3
Question how can I make sure I get all the results correct for $query2->result_array().
Image
Get function
public function get_events($year, $month) {
$calendar = array();
$this->db->select('*');
$this->db->from('events');
$this->db->where('year', $year);
$this->db->where('month', $month);
$query1 = $this->db->get();
foreach ($query1->result_array() as $event) {
$this->db->select('*');
$this->db->from('extra_events');
$this->db->where('events_id', $event['events_id']);
$this->db->where('year', $year);
$this->db->where('month', $month);
//$this->db->limit(2);
$query2 = $this->db->get();
foreach ($query2->result_array() as $result) {
if (array_key_exists($event['day'], $calendar)) {
$calendar[$event['day']] = $calendar[$event['day']] . '<br/>' . $result['event'];
} else {
$calendar[$event['day']] = '<br/><b>From Events Table</b> <i class="fa fa-long-arrow-down"></i><br/>' . $event['event'] . '<hr><b>From Extra Events Table</b> <i class="fa fa-long-arrow-down"></i>' ;
}
}
}
return $calendar;
}
Database
Solved Now
I have had to create two tables and then on the model function added this line
$calendar[$event['day']] = '<br/>' . $event['event'];
Below first foreach for the main event and then any other extra events use the second foreach with array key exists.
This now also lets me control how many rows are now displayed in extra
events foreach loop.
public function get_calendar_events($year, $month) {
$calendar = array();
$events = $this->get_events($year, $month);
foreach($events as $event) {
// Added line for main calendar event
$calendar[$event['day']] = '<br/>' . $event['event'];
// Passes main event id to extra_events get function
$extra_events = $this->get_extra_events($event['events_id']);
// checks if array key exists for extra event in side foreach loop
foreach($extra_events as $extra_event) {
if (array_key_exists($extra_event['day'], $calendar)) {
$calendar[$extra_event['day']] = $calendar[$extra_event['day']] . '<br/>' . $extra_event['event'];
} else {
$calendar[$extra_event['day']] = $extra_event['event'];
}
}
}
return $calendar;
}
Calendar Model
<?php
class Model_calendar extends CI_Model {
public function add_event() {
$data = array(
'year' => $this->input->post('year'),
'month' => ($this->input->post('month') > 10) ? $this->input->post('month') : '0' . $this->input->post('month'),
'day' => $this->input->post('day'),
'date' => $this->input->post('year') .'-'. $this->input->post('month') .'-'. $this->input->post('day'),
'event' => $this->input->post('event'),
'date_added' => mdate('%Y-%m-%d %H:%i:%s', now())
);
$this->db->insert($this->db->dbprefix . 'events', $data);
}
public function add_extra_event() {
$data = array(
'events_id' => (int)$this->get_event_id(),
'year' => $this->input->post('year'),
'month' => ($this->input->post('month') > 10) ? $this->input->post('month') : '0' . $this->input->post('month'),
'day' => $this->input->post('day'),
'date' => $this->input->post('year') .'-'. $this->input->post('month') .'-'. $this->input->post('day'),
'event' => $this->input->post('event'),
'date_added' => mdate('%Y-%m-%d %H:%i:%s', now())
);
$this->db->insert($this->db->dbprefix . 'extra_events', $data);
}
public function get_event_id() {
$this->db->where('year', $this->input->post('year'));
$this->db->where('month', ($this->input->post('month') > 10) ? $this->input->post('month') : '0' . $this->input->post('month'));
$this->db->where('day', $this->input->post('day'));
$query = $this->db->get($this->db->dbprefix . 'events');
if ($query->num_rows() > 0) {
$row = $query->row();
return $row->events_id;
} else {
return false;
}
}
public function check_event() {
$this->db->where('year', $this->input->post('year'));
$this->db->where('month', ($this->input->post('month') > 10) ? $this->input->post('month') : '0' . $this->input->post('month'));
$this->db->where('day', $this->input->post('day'));
$query = $this->db->get($this->db->dbprefix . 'events');
if ($query->num_rows() > 0) {
return TRUE;
} else {
return FALSE;
}
}
public function delete_events() {
$this->db->where("date <", date('Y-m-d'));
$this->db->delete($this->db->dbprefix . 'events');
}
public function delete_extra_events() {
$this->db->where("date <", date('Y-m-d'));
$this->db->delete($this->db->dbprefix . 'extra_events');
}
public function get_calendar_events($year, $month) {
$calendar = array();
$events = $this->get_events($year, $month);
foreach($events as $event) {
$calendar[$event['day']] = '<br/>' . $event['event'];
$extra_events = $this->get_extra_events($event['events_id']);
foreach($extra_events as $extra_event) {
if (array_key_exists($extra_event['day'], $calendar)) {
$calendar[$extra_event['day']] = $calendar[$extra_event['day']] . '<br/>' . $extra_event['event'];
} else {
$calendar[$extra_event['day']] = $extra_event['event'];
}
}
}
return $calendar;
}
public function get_events($year, $month) {
$this->db->where('year', $year);
$this->db->where('month', $month);
$events = $this->db->get($this->db->dbprefix . 'events');
return $events->result_array();
}
public function get_extra_events($events_id) {
$this->db->limit(5);
$this->db->where('events_id', $events_id);
$extra_events = $this->db->get($this->db->dbprefix . 'extra_events');
return $extra_events->result_array();
}
}
Calendar Controller
<?php
class Calendar extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('dashboard/model_calendar');
$this->load->library('calendar');
$this->load->library('form_validation');
}
public function index() {
if ($this->uri->segment(3) == FALSE) {
$year = date('Y');
} else {
$year = $this->uri->segment(3);
}
if ($this->uri->segment(4) == FALSE) {
$month = date('m');
} else {
$month = $this->uri->segment(4);
}
$prefs = array(
'start_day' => 'monday',
'show_next_prev' => true,
'month_type' => 'long',
'day_type' => 'long',
'next_prev_url' => base_url('dashboard/calendar')
);
$prefs['template'] = '
{table_open}<div class="table-responsive"><table border="0" cellpadding="0" cellspacing="0" class="table table-hover table-striped table-bordered calendar">{/table_open}
{heading_row_start}<tr>{/heading_row_start}
{heading_previous_cell}<th><i class="fa fa-chevron-left fa-2x "></i></th>{/heading_previous_cell}
{heading_title_cell}<th class="text-center" colspan="{colspan}">{heading}</th>{/heading_title_cell}
{heading_next_cell}<th class="text-right "><i class="fa fa-chevron-right fa-2x"></i></th>{/heading_next_cell}
{heading_row_end}</tr>{/heading_row_end}
{week_row_start}<tr >{/week_row_start}
{week_day_cell}<td class="text-center" style="height: 5rem;">{week_day}</td>{/week_day_cell}
{week_row_end}</tr>{/week_row_end}
{cal_row_start}<tr class="days">{/cal_row_start}
{cal_cell_start}<td class="day">{/cal_cell_start}
{cal_cell_content}
<div class="day_number">{day}</div>
<div class="content" style="margin-top: 0;">{content}</div>
{/cal_cell_content}
{cal_cell_content_today}
<div class="day_number highlight">{day}</div>
<div class="content" style="margin-top: 0;">{content}</div>
{/cal_cell_content_today}
{cal_cell_no_content}
<div class="day_number">{day}</div>
{/cal_cell_no_content}
{cal_cell_no_content_today}
<div class="day_number highlight">{day}</div>
{/cal_cell_no_content_today}
{cal_cell_blank} {/cal_cell_blank}
{cal_cell_end}</td>{/cal_cell_end}
{cal_row_end}</tr>{/cal_row_end}
{table_close}</table></div>{/table_close}
';
$this->calendar->initialize($prefs);
$this->model_calendar->delete_events();
$this->model_calendar->delete_extra_events();
$events = $this->model_calendar->get_calendar_events($year, $month);
$data['calendar'] = $this->calendar->generate($year, $month, $events);
if ($this->uri->segment(3) == TRUE) {
$data['view_more'] = site_url('report/events/'. $year .'/'. $month);
} else {
$data['view_more'] = site_url('report/events');
}
$this->form_validation->set_rules('event', 'Calendar Event', 'trim|required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('dashboard/calender_view', $data);
} else {
if ($this->model_calendar->check_event() == TRUE) {
$this->model_calendar->add_extra_event();
} else {
$this->model_calendar->add_event();
}
$this->session->set_flashdata('added_event', '<i class="fa fa-check-circle"></i> You have added event to your calendar!');
redirect('common/dashboard');
}
}
}
You can limit foreach to get just 2 events.
limiting foreach loop in get_events() function.
public function get_events($year, $month) {
$calendar = array();
$this->db->where('year', $year);
$this->db->where('month', $month);
$query = $this->db->get('events');
$results = $query->result_array();
$i = 0;
foreach ($results as $event) {
if ($i < 2) { // getting / fetching / extracting value from foreach for 2 times only
if (array_key_exists($event['day'], $calendar)) {
$calendar[$event['day']] = $calendar[$event['day']] . '
<hr/>
<div class="text-center">
<span class="label label-info">New</span>
</div>
<br/>
<div class="clearfix">
<div class="pull-left">
<ul class="list-unstyled text-center">
<li >'
. word_limiter(anchor(base_url('report/events/' . $year . '/' . $month . '/?event_id=' . $event['events_id']), $event['event']), 4) . '
</li>
</ul>
</div>
<div class="pull-right">
<form id="form-event" action="' . base_url('dashboard/calendar') . '" class="form-inline" method="post" enctype="multipart/form-data" onsubmit="return confirm(\'Are you sure you want to remove this!\')";>
<input type="hidden" name="delete_id" value="' . $event['events_id'] . '">
<i class="fa fa-pencil"></i>
<button type"submit" class="btn btn-danger"><i class="fa fa-trash"></i></button>
</form>
</div>
</div>';
} else {
$calendar[$event['day']] = '
<div class="text-center">
<span class="label label-info">New</span>
</div>
<br/>
<div class="clearfix">
<div class="pull-left">
<ul class="list-unstyled text-center">
<li >'
. word_limiter(anchor(base_url('report/events/' . $year . '/' . $month . '/?event_id=' . $event['events_id']), $event['event']), 4) . '
</li>
</ul>
</div>
<div class="pull-right">
<form id="form-event" action="' . base_url('dashboard/calendar') . '" class="form-inline" method="post" enctype="multipart/form-data" onsubmit="return confirm(\'Are you sure you want to remove this!\')";>
<input type="hidden" name="delete_id" value="' . $event['events_id'] . '">
<i class="fa fa-pencil"></i>
<button type"submit" class="btn btn-danger"><i class="fa fa-trash"></i></button>
</form>
</div>
</div>
';
}
$i++;
}
}
return $calendar;
}

html form with php issue

I have made a html form where the user can enter his name/email/phone etc. and also select quantity of the listed products.
Here is the product code and I'm wondering how do I do to include in the email message I get from the form to include how many of what product the user wants.
This is the form code:
<div class="col-sm-6 col-md-6 bottom-padding">
<?php
process_si_contact_form();
if (isset($_SESSION['ctform']['error']) && $_SESSION['ctform']['error'] == true):
?>
<div class="alert alert-danger">
<strong>Oops!</strong> Something went wrong.
</div>
<?php
elseif (isset($_SESSION['ctform']['success']) && $_SESSION['ctform']['success'] == true):
?>
<div class="alert alert-success">
<strong>Message sent!</strong> We'll get in touch asap.
</div>
<?php
endif;
?>
<form class="form-box register-form contact-form" method="POST" id="contact_form">
<input type="hidden" name="do" value="contact" />
<h3 class="title">Form</h3>
<label>Name: <span class="required">*</span></label>
<?php echo #$_SESSION['ctform']['f_name_error'] ?>
<input class="form-control" type="text" name="ct_f_name" value="<?php echo htmlspecialchars(#$_SESSION['ctform']['ct_f_name']) ?>">
<label>E-mail: <span class="required">*</span></label>
<?php echo #$_SESSION['ctform']['f_email_error'] ?>
<input class="form-control" type="email" name="ct_f_email" value="<?php echo htmlspecialchars(#$_SESSION['ctform']['ct_f_email']) ?>">
<label>Phone: <span class="required">*</span></label>
<?php echo #$_SESSION['ctform']['f_tel_error'] ?>
<input class="form-control" type="text" name="ct_f_tel" value="<?php echo htmlspecialchars(#$_SESSION['ctform']['ct_f_tel']) ?>">
<div class="panel-group" id="accordion">
<div class="panel panel-info">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" class="collapsed">
Hardware
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse" style="height: 0px;">
<div class="panel-body">
<ul class="list-group checked-list-box">
<?php
$my_products = array(
'1' => 'Product 1',
'2' => 'Product 2',
'3' => 'Product 3'
);
foreach ($my_products as $key => $value) {
echo "<div class=\"col-xs-6\" style=\"margin: 10px 0 5px 0;\">";
echo "<li class=\"list-group-item\" data-style=\"button\">";
echo $value;
echo "<select class=\"form-control\" name=\"quantity[$key]>\"";
for ($i = 0; $i <= 10; $i++) echo "<option value=\"$i\">$i</option>";
echo "</select>";
echo "</li>";
echo "</div>";
}
?>
</ul>
</div>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" class="collapsed">
Software
</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse">
<div class="panel-body">
Empty.
</div>
</div>
</div>
</div>
<label>Message: <span class="required">*</span></label>
<?php echo #$_SESSION['ctform']['message_error'] ?>
<textarea class="form-control" name="ct_message"><?php echo htmlspecialchars(#$_SESSION['ctform']['ct_message']) ?></textarea>
<div class="clearfix"></div>
<div class="buttons-box clearfix">
<input type="submit" class="btn btn-default" value="Send">
<span class="required"><b>*</b> Required fields</span>
</div>
</form>
</div>
Anything else I need to post? I don't know if this is the best way coded but it does the work. Now it won't let me save this question because it's much code included in this post so I'm writing to be able to save it lol.
EDIT: ADDING PHP FORM CODE.
<?php
function process_si_contact_form() {
$_SESSION['ctform'] = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && #$_POST['do'] == 'contact') {
foreach($_POST as $key => $value) {
if (!is_array($key)) {
if ($key != 'ct_message') $value = strip_tags($value);
$_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
}
}
$f_name = #$_POST['ct_f_name'];
$f_tel = #$_POST['ct_f_tel'];
$f_email = #$_POST['ct_f_email'];
$message = #$_POST['ct_message'];
$f_name = substr($f_name, 0, 64);
$errors = array();
if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) {
if (strlen($f_name) < 3) {
$errors['f_name_error'] = 'Your name please.';
}
if (strlen($f_tel) < 10) {
$errors['f_tel_error'] = 'Your phone please.';
} else if (!preg_match('/^([-+0-9()]+)$/', $f_tel)) {
$errors['f_tel_error'] = 'Thats not a phone number!';
}
if (strlen($f_email) == 0) {
$errors['f_email_error'] = 'Your e-mail please.';
} else if (!preg_match('/^(?:[\w\d]+\.?)+#(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/i', $f_email)) {
$errors['f_email_error'] = 'Thats not an e-mail!';
}
if (strlen($message) < 10) {
$errors['message_error'] = 'Your message must contain atleast 10 characters.';
}
}
if (sizeof($errors) == 0) {
$time = date('r');
$message = "<strong>Name:</strong><br /><em>$f_name</em><br />"
. "<br />"
. "<strong>E-mail:</strong><br /><em>$f_email</em><br />"
. "<br />"
. "<strong>Phone:</strong><br /><em>$f_tel</em>"
. "<br /><br /><br />"
. "<strong>Message:</strong><br />"
. "<pre>$message</pre>"
. "<br /><br />"
. "<strong>IP:</strong><br /><em>{$_SERVER['REMOTE_ADDR']}</em><br />"
. "<br />"
. "<strong>Time:</strong><br /><em>$time</em><br />"
. "<br />"
. "<strong>Browser:</strong><br /><em>{$_SERVER['HTTP_USER_AGENT']}</em>";
$message = wordwrap($message, 70);
if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) {
mail($GLOBALS['ct_recipient'], $GLOBALS['ct_msg_subject'], $message, "From: {$GLOBALS['ct_recipient_no_reply']}\r\nReply-To: {$f_email}\r\nContent-type: text/html; charset=utf8\r\nMIME-Version: 1.0");
}
$_SESSION['ctform']['error'] = false;
$_SESSION['ctform']['success'] = true;
} else {
$_SESSION['ctform']['ct_f_name'] = $f_name;
$_SESSION['ctform']['ct_f_tel'] = $f_tel;
$_SESSION['ctform']['ct_f_email'] = $f_email;
$_SESSION['ctform']['ct_message'] = $message;
foreach($errors as $key => $error) {
$_SESSION['ctform'][$key] = "<span class=\"error\" style=\"float: right; color: 00ff00;\">$error</span>";
}
$_SESSION['ctform']['error'] = true;
}
}
}
$_SESSION['ctform']['success'] = false;
?>
EDIT 2: ADDING NEW PHP MAIL CODE.
<?php
function process_si_contact_form() {
$_SESSION['ctform'] = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && #$_POST['do'] == 'contact') {
foreach($_POST as $key => $value) {
if (!is_array($key)) {
if ($key != 'ct_message') $value = strip_tags($value);
$_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
}
}
$f_name = #$_POST['ct_f_name'];
$f_tel = #$_POST['ct_f_tel'];
$f_email = #$_POST['ct_f_email'];
$message = #$_POST['ct_message'];
$f_name = substr($f_name, 0, 64);
$products = array(
#$_POST['quantity[1]'],
#$_POST['quantity[2]'],
#$_POST['quantity[3]'],
#$_POST['quantity[4]'],
#$_POST['quantity[5]'],
#$_POST['quantity[6]'],
#$_POST['quantity[7]'],
#$_POST['quantity[8]'],
#$_POST['quantity[9]'],
#$_POST['quantity[10]']);
$errors = array();
if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) {
if (strlen($f_name) < 3) {
$errors['f_name_error'] = 'Fyll i ditt namn';
}
if (strlen($f_tel) < 10) {
$errors['f_tel_error'] = 'Fyll i ditt tel.nr';
} else if (!preg_match('/^([-+0-9()]+)$/', $f_tel)) {
$errors['f_tel_error'] = 'Felaktigt tel.nr';
}
if (strlen($f_email) == 0) {
$errors['f_email_error'] = 'Fyll i din e-postadress';
} else if (!preg_match('/^(?:[\w\d]+\.?)+#(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/i', $f_email)) {
$errors['f_email_error'] = 'Felaktig e-postadress';
}
if (strlen($message) < 10) {
$errors['message_error'] = 'Ditt meddelande måste bestå av minst 10 tecken';
}
}
if (sizeof($errors) == 0) {
$time = date('r');
$message = "<strong>Namn:</strong><br /><em>$f_name</em><br />"
. "<br />"
. "<strong>E-postadress:</strong><br /><em>$f_email</em><br />"
. "<br />"
. "<strong>Telefon:</strong><br /><em>$f_tel</em>"
. "<br /><br /><br />"
. "<strong>Meddelande:</strong><br />"
. "<pre>$message</pre>"
. "<br />"
. "<strong>IP:</strong><br /><em>{$_SERVER['REMOTE_ADDR']}</em><br />"
. "<br /><strong>".$products[1]." - Ingenico IPP350</strong>"
. "<br /><strong>".$products[2]." - Ingenico ICT250</strong>"
. "<br /><strong>".$products[3]." - Yomani</strong>"
. "<br /><strong>".$products[4]." - Ingenico IWL250 GPRS</strong>"
. "<br /><strong>".$products[5]." - PosBank® AnyShop II</strong>"
. "<br /><strong>".$products[6]." - Ingenico IWL250 Wifi</strong>"
. "<br /><strong>".$products[7]." - Ingenico IWL250 BT</strong>"
. "<br /><strong>".$products[8]." - PosBank&reg AnyShop e2</strong>"
. "<br /><strong>".$products[9]." - Ingenico IWL285 3G</strong>"
. "<br /><strong>".$products[10]." - Ingenico iCMP</strong>"
. "<br /><br /><strong>Tid:</strong><br /><em>$time</em><br />"
. "<br />"
. "<strong>Webbläsare:</strong><br /><em>{$_SERVER['HTTP_USER_AGENT']}</em>";
$message = wordwrap($message, 70);
if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) {
mail($GLOBALS['ct_recipient'], $GLOBALS['ct_msg_subject'], $message, "From: {$GLOBALS['ct_recipient_no_reply']}\r\nReply-To: {$f_email}\r\nContent-type: text/html; charset=utf8\r\nMIME-Version: 1.0");
}
$_SESSION['ctform']['error'] = false;
$_SESSION['ctform']['success'] = true;
} else {
$_SESSION['ctform']['ct_f_name'] = $f_name;
$_SESSION['ctform']['ct_f_tel'] = $f_tel;
$_SESSION['ctform']['ct_f_email'] = $f_email;
$_SESSION['ctform']['ct_message'] = $message;
foreach($errors as $key => $error) {
$_SESSION['ctform'][$key] = "<span class=\"error\" style=\"float: right; color: 00ff00;\">$error</span>";
}
$_SESSION['ctform']['error'] = true;
}
}
}
$_SESSION['ctform']['success'] = false;
?>
The name of these elements would be: quantity[0], quantity[1], and quantity[2] which contains the value gave for each product. Notice if you want a quantity[0] you need to include that in the $my_products array. The value for Product 1 would be in quantity[1]. The information is from this code here:
$my_products = array(
'0' => 'Product 0', /* Added Product 0 */
'1' => 'Product 1',
'2' => 'Product 2'
);
foreach ($my_products as $key => $value) {
...
// $key is 0,1,2 through the loop so the name would be
// quantity[0] quantity[1], and quantity[2]
echo "<select class=\"form-control\" name=\"quantity[$key]>\"";
for ($i = 0; $i <= 10; $i++) echo "<option value=\"$i\">$i</option>";
echo "</select>";
...
}
So you would just get name in the same way you got your other POST data in your PHP form code:
$products = array(
#$_POST['quantity[0]'],
#$_POST['quantity[1]'],
#$_POST['quantity[2]'] );
Now just include those values in your $message:
$message =
/* Your normal message content here from the code */
. "<strong>Product0:</strong><br /><em>".$products[0]."</em><br />"
. "<br />"
. "<strong>Product1:</strong><br /><em>".$products[1]".</em><br />"
. "<br />"
. "<strong>Product2:</strong><br /><em>".$products[2]."</em><br />"
. "<br />";

multiple inputs - Problems with array

it is such that I need to use multiple inputs on my side,
I've tried to do like this but it does not work as it will not show up on the page at all in some manner.
HTML
<div id="onlinetestside">
<div id="onlinetestsidealt"><?php echo $ordet;?></div>
<input type="text" name="ord[]" maxlength="190">
<div style="clear:both;"></div>
</div>
PHP
//ordetalt its coming from database.
$alt = $_POST["ord"];
if($ordetalt == $alt)
{
echo $ordetalt . " og " . $alt;
}
else
{
echo "Error " . $ordetalt . " and " . $alt;
}
error appears like this:
Error Hej and Array
What I want to get to it shall be such that "$ordetalt == $alt" have the same content and it fits together.
EIDT
Here I show the entire code where I need to download some code to the side.
if ($stmt = $this->mysqli->prepare('SELECT id, ordet, ordetalt FROM test WHERE getid = ?')) {
$stmt->bind_param('i', $id);
$id = $_GET['id'];
$stmt->execute();
$stmt->bind_result($id, $ordet, $ordetalt);
while ($stmt->fetch()) {
?>
<div id="onlinetestside">
<div id="onlinetestsidealt"><?php echo $ordet;?></div>
<input type="text" name="ord[]" maxlength="190">
<div style="clear:both;"></div>
</div>
<?php
//ordetalt its coming from database
$alt = $_POST["ord"];
if($ordetalt == $alt)
{
echo $ordetalt . " og " . $alt;
}
else
{
echo "Error " . $ordetalt . " and " . $alt;
}
}
$stmt->close();
}
EIDT EIDT
$i = 0;
$a = $i++;
$alt = $_POST["ord"][$a];
if($ordetalt == $alt)
{
echo $ordetalt . " og " . $alt;
}
else
{
echo "Error " . $ordetalt . " and " . $alt;
}
Barmar is spot on, your line
$alt = $_POST["ord"];
Should read
$alt = $_POST["ord"][0];
OR
change your html like so:
<div id="onlinetestside">
<div id="onlinetestsidealt"><?php echo $ordet;?></div>
<input type="text" name="ord" maxlength="190">
<div style="clear:both;"></div>
</div>

Categories