PHPSpreadsheet generates empty file if it containts more than 16 rows - php

I am generating a xlsx file with PHPspreadshet and it always gives me an empty file (0kb) when it has more than 16 rows. I already tried to search for erros etc. and found nothing. It just depends on the row.
The Spreadsheet (Html for testing):
And when I switch following lines:
$this->sheet->setCellValue("A16", "Besetzt");
To
$this->sheet->setCellValue("A17", "Besetzt");
The generator (execute() is the entry point):
class ExcelOperation extends AbstractOperation
{
private function addWork($cell, $name = "", $phone = ""){
if($cell != null){
$richText = new \PhpOffice\PhpSpreadsheet\RichText\RichText();
$boldText = $richText->createText($name);
//$boldText->getFont()->setBold(true);
$richText->createText("\n".$phone);
$this->sheet->getCell($cell)->setValue($richText);
$this->sheet->getStyle($cell)->getAlignment()->setWrapText(true);
$this->sheet->getStyle($cell)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
}
}
public function execute(WebRequest $wreq, WebResponse $wres){
$eventId = $wreq->getParameter();
$userId = "1839357067871549236";
$calendar = $this->getCalendar($userId, $eventId);
$eventStatistics = $this->getEventStatistics($eventId);
//All Positions
$this->renderPositionData($calendar);
//$this->renderCurrentStatus($eventStatistics);
$this->formatColumn("A");
$this->formatColumn("B");
$this->formatColumn("C");
$this->formatColumn("D");
//$writer = new Xlsx($this->spreadsheet);
$writer = new Html($this->spreadsheet);
$wres->success(true);
$wres->set("filename", "Schichtplan.html");
$wres->set("file", $writer->save('php://output'));
}
private function addFullBorder($from, $to){
/*$styleArray = array(
'borders' => array(
'outline' => array(
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
'color' => array('argb' => PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLACK),
),
),
);
$this->sheet ->getStyle($from.':'.$to)->applyFromArray($styleArray);*/
}
private function renderCurrentStatus($statistics){
$this->sheet->setCellValue("F2", "Stand");
$this->sheet->mergeCells('F2:G2');
$this->sheet->getStyle("F2")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
$this->sheet->getStyle("F2")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
$this->sheet->getStyle("F2")->getFill()->getStartColor()->setRGB("A4DDF5");
$this->sheet->getStyle("F2")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$frei = $statistics["gesamt"]-($statistics["warten"]+$statistics["besetzt"]);
$this->sheet->setCellValue("F2", "Frei");
$this->sheet->setCellValue("G2", $frei);
$this->sheet->setCellValue("F4", "Besetzt");
$this->sheet->setCellValue("G4", $statistics["besetzt"]);
$this->sheet->setCellValue("F6", "Wartend");
$this->sheet->setCellValue("G6", $statistics["warten"]);
$this->sheet->setCellValue("F8", "Gesamt");
$this->sheet->setCellValue("G8", $statistics["gesamt"]);
$this->addFullBorder("F2", "G8");
}
private function renderPositionData($calendar){
foreach($calendar as $positionId => $position){
$positionName = $position["position"]["alle_positionen_description"];
preg_match('/Pos\. [0-9]+/', $positionName, $matches);
$positionEndCell = null;
$actualCol = $this->positionCount%$this->positionsPerLine;
if(isset($matches[0])){
$shortPositionName = $matches[0];
}else{
$shortPositionName = $positionName;
}
if($actualCol <5){
$cell = $this->getCell($actualCol, $this->actualRowPerPosition);
//var_dump($cell);
//For Position header
$this->actualRowPerPosition[$actualCol] += 1;
$this->addPositionHeader($cell, $shortPositionName);
$positionStartCell = $cell;
//All shifts within this job
foreach($position["jobs"] as $job){
//For Each Shift in Position
$cell = $this->getCell($actualCol, $this->actualRowPerPosition);
//$cell = "A17";
//var_dump($cell);
$this->sheet->setCellValue("A17", "Besetzt");
$formattedDateFrom = $this->dbDateToTime($job["job"]["alle_schichten_start"]);
$formattedDateTo = $this->dbDateToTime($job["job"]["alle_schichten_ende"]);
$this->addShiftHeader($cell, $formattedDateFrom." - ".$formattedDateTo);
$this->actualRowPerPosition[$actualCol] = 18;
$positionEndCell = $cell;
foreach($job["workers"] as $worker){
$fullName = $worker["firstname"]." ".$worker["secondname"];
$phone = "+43";
$cell = $this->getCell($actualCol, $this->actualRowPerPosition);
$this->addWork($cell, $fullName, $phone);
//$this->actualRowPerPosition[$actualCol] += 1;
$positionEndCell = $cell;
}
}
if($positionEndCell == null){
$positionEndCell = $positionStartCell;
}
$this->addFullBorder($positionStartCell, $positionEndCell);
$this->positionCount++;
}
}
}
private function formatColumn($columnName){
$this->sheet->getColumnDimension($columnName)->setWidth(35);
}
private function dbDateToTime(string $dateTime){
$date = new \DateTime($dateTime);
$formattedDateFrom = $date->format('H:i');
return $formattedDateFrom;
}
private function getCell($actualCol, $actualRowPerPosition){
$actualRow = $actualRowPerPosition[$actualCol]+1;
$actualColName = $this->getColName($actualCol);
$cell = $actualColName.$actualRow;
$this->sheet->getRowDimension($actualRow)->setRowHeight(30);
return $cell;
}
private function addPositionHeader($cell, $positionName){
$this->sheet->setCellValue($cell, $positionName);
//Font Color
$this->sheet->getStyle($cell)->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$this->sheet->getStyle($cell)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
//Background Color
$this->sheet->getStyle($cell)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
$this->sheet->getStyle($cell)->getFill()->getStartColor()->setRGB("A4DDF5");
}
private function addShiftHeader($cell, $shiftText){
$this->sheet->setCellValue($cell, $shiftText);
$this->sheet->getStyle($cell)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
}
private function getColName($colId){
$cols = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"];
return $cols[$colId];
}
private function getCalendar($userId, $eventId){
$dbManager = new DbManager();
$jobs = $dbManager->getAdminCalendarForUser($eventId, $userId);
$calendar = $this->generateCalendarArray($jobs);
return $calendar;
}
private function getEventStatistics($eventId){
$dbManager = new DbManager();
$eventStatistics = $dbManager->getEventStatistics($eventId);
return $eventStatistics;
}
private function generateCalendarArray($jobs){
$dbManager = new DbManager();
$calendar = [];
foreach ($jobs as $job) {
if(!isset($calendar[$job["alle_positionen_id"]])){
$jobFieldsWithValues = $this->getJobFieldsWithValues($dbManager, $job["alle_positionen_id"]);
$job["needs_approval"] = $job["needs_approval"] ? true : false;
$calendar[$job["alle_positionen_id"]] =
[
"position" =>$job,
"jobFieldsWithValues"=> $jobFieldsWithValues,
"jobs" => [],
"positionPermission"=>$job["positionPermission"]
];
}
//Check if position has shift
if($job["alle_schichten_id"] != null){
//Check if job in this shift (falsely defined as job) exists
if(!isset($calendar[$job["alle_positionen_id"]]["jobs"][$job["alle_schichten_id"]])){
$calendar[$job["alle_positionen_id"]]["jobs"][$job["alle_schichten_id"]] = [
"job"=>$job,
"workers"=>[]
];
}
if($job["Email"] != null){
$jobDef = [
"email"=>$job["Email"],
"approved"=>$job["Approved"],
"userId"=>$job["id"]."",
"firstname"=>$job["Vorname"],
"secondname"=>$job["Nachname"]
];
array_push($calendar[$job["alle_positionen_id"]]["jobs"][$job["alle_schichten_id"]]["workers"], $jobDef);
}
}
}
return $calendar;
}
private function getJobFieldsWithValues(DbManager $dbManager, int $positionId) : array{
$jobFieldsWithValues = [];
$jobFields = $dbManager->getJobFieldsWithValues($positionId);
foreach ($jobFields as $jobField) {
if(isset($jobFieldsWithValues[$jobField["id"]])){
array_push($jobFieldsWithValues[$jobField["id"]]["values"], ["data-value"=>$jobField["value"], "value"=>$jobField["value"]]);
}else{
$jobFieldsWithValues[$jobField["id"]] = [
"id"=>$jobField["id"],
"fieldBaseType"=>$jobField["fieldDataType"],
"name"=>$jobField["Bezeichnung"],
"description"=>$jobField["description"],
"values"=>[]];
array_push($jobFieldsWithValues[$jobField["id"]]["values"], ["data-value"=>$jobField["value"], "value"=>$jobField["value"]]);
}
}
return $jobFieldsWithValues;
}
public function __construct() {
$this->spreadsheet = new Spreadsheet();
$this->sheet = $this->spreadsheet->getActiveSheet();
$this->positionsPerLine = 4;
$this->actualRowPerPosition = [0,0,0,0];
$this->positionCount = 0;
$this->colors = [
"black"=>\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLACK
];
}
}
It generates an empty file.

Related

Auto Merge Row Data in Maatwebsite Export Excel

I have dynamic data that will be exported into excel using maatwebsite. I have a case where I need to merge the same data. How can I do it from a collection?
From This:
To This:
class PerencanaanExport implements
FromCollection,
WithCustomStartCell,
WithEvents,
ShouldAutoSize,
WithStyles
{
/**
* #return \Illuminate\Support\Collection
*/
public function __construct(string $tahun)
{
$this->tahun = $tahun;
}
public function startCell(): string
{
return "A3";
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
/** #var Sheet $sheet */
$tahun =
$this->tahun == "null"
? ""
: ($this->tahun == "all"
? ""
: $this->tahun);
$sheet = $event->sheet;
$sheet->mergeCells("A1:E1");
$sheet->setCellValue("A1", "Kode");
$sheet->setCellValue("A2", "Urusan");
$sheet->setCellValue("B2", "Bidang Urusan");
$sheet->setCellValue("C2", "Program");
$sheet->setCellValue("D2", "Kegiatan");
$sheet->setCellValue("E2", "Sub Kegiatan");
$sheet->mergeCells("F1:F2");
$sheet->setCellValue(
"F1",
"Urusan/ Bidang Urusan Pemerintahan Daerah dan Program Kegiatan"
);
$sheet->mergeCells("G1:G2");
$sheet->setCellValue(
"G1",
"Indikator Kinerja Program/ Kegiatan"
);
$sheet->mergeCells("H1:K1");
$sheet->setCellValue("H1", "Rencana Tahun " . $tahun);
$sheet->setCellValue("H2", "LOKASI");
$sheet->setCellValue("I2", "TARGET KINERJA");
$sheet->setCellValue("J2", "ANGGARAN");
$sheet->setCellValue("K2", "SUMBER DANA");
$styleArray = [
"borders" => [
"allBorders" => [
"borderStyle" =>
\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
"color" => ["argb" => "000000"],
],
],
];
$cellRange = "A1:K" . $sheet->getHighestRow(); // All headers
$event->sheet
->getDelegate()
->getStyle($cellRange)
->applyFromArray($styleArray);
$event->sheet
->getStyle("A1:K2")
->getAlignment()
->setVertical(StyleAlignment::VERTICAL_TOP)
->setHorizontal(StyleAlignment::VERTICAL_CENTER)
->setWrapText(true);
},
];
}
public function collection()
{
$arr = [];
$tahun = $this->tahun;
$jointahun = "";
if ($tahun) {
$jointahun = " AND d.tahun =" . $tahun;
}
$query = "XXXXX";
$query .= "XXXXX";
$data = DB::select($query);
$oldProgram = "";
$oldKegiatan = "";
foreach ($data as $key => $value) {
if ($key != 0) {
$oldProgram = $data[$key - 1]->program;
$oldKegiatan = $data[$key - 1]->kegiatan;
}
if ($oldProgram != $value->program) {
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
"",
"",
$value->program,
]);
}
if ($oldKegiatan != $value->kegiatan) {
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
$value->kode_kegiatan,
"",
$value->kegiatan,
$value->indikator_kegiatan,
]);
}
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
$value->kode_kegiatan,
$value->kode_sub_kegiatan,
$value->sub_kegiatan,
$value->indikator_perencanaan,
$value->lokasi,
$value->target_kinerja,
$value->anggaran,
$value->sumber_dana,
]);
}
return collect($arr);
}
public function styles(Worksheet $sheet)
{
$sheet
->getStyle("1:2")
->getFont()
->setBold(true);
}

I think I found a bug with setValue from ReflectionProperty

I'm working on a function to recursively remove arrays and objects recursively. The problem is that certain recursions may be inside private properties of objects.
below is what I tried as well as the entries I tried to use.
this is my entrie
class TestOBJ{
private $fooClosure = null;
public $bar = 5;
private $myPrivateRecursion = null;
private $aimArrayAndContainsRecursion = [];
public function __construct()
{
$this->fooClosure = function(){
echo 'pretty closure';
};
}
public function setMyPrivateRecursion(&$obj){
$this->myPrivateRecursion = &$obj;
}
public function setObjInsideArray(&$obj){
$this->aimArrayAndContainsRecursion[] = &$obj;
}
}
$std = new stdClass();
$std->std = 'any str';
$std->obj = new stdClass();
$std->obj->other = &$std;
$obj = new TestOBJ();
$obj->bar = new TestOBJ();
$obj->bar->bar = 'hey brow, please works';
$obj->bar->setMyPrivateRecursion($std);
my entrie is var $obj
and this is my function / solution
function makeRecursionStack($vector, &$stack = [], $from = null)
{
if ($vector) {
if (is_object($vector) && !in_array($vector, $stack, true) && !is_callable($vector)) {
$stack[] = &$vector;
if (get_class($vector) === 'stdClass') {
foreach ($vector as $key => $value) {
if (in_array($vector->{$key}, $stack, true)) {
$vector->{$key} = null;
} else {
$vector->{$key} = $this->makeRecursionStack($vector->{$key}, $stack, $key);
}
}
return $vector;
} else {
$object = new \ReflectionObject($vector);
$reflection = new \ReflectionClass($vector);
$properties = $reflection->getProperties();
if ($properties) {
foreach ($properties as $property) {
$property = $object->getProperty($property->getName());
$property->setAccessible(true);
if (!is_callable($property->getValue($vector))) {
$private = false;
if ($property->isPrivate()) {
$property->setAccessible(true);
$private = true;
}
if (in_array($property->getValue($vector), $stack, true)) {
$property->setValue($vector, null);
} else {
//if($property->getName() === 'myPrivateRecursion' && $from === 'bar'){
//$get = $property->getValue($vector);
//$set = $this->makeRecursionStack($get, $stack, $property->getName());
//$property->setValue($vector, $set);
//pre_clear_buffer_die($property->getValue($vector));
//}
$property->setValue($vector, $this->makeRecursionStack($property->getValue($vector), $stack, $property->getName()));
}
if ($private) {
$property->setAccessible(false);
}
}
}
}
return $vector;
}
} else if (is_array($vector)) {
$nvector = [];
foreach ($vector as $key => $value) {
$nvector[$key] = $this->makeRecursionStack($value, $stack, $key);
}
return $nvector;
} else {
if (is_object($vector) && !is_callable($vector)) {
return null;
}
}
}
return $vector;
}
The place where I have comments is where I noticed the problem. if the If is not commented there $get would receive a stdClass that has recursion and this works perfectly and $set would receive the stdClass without recursion. In that order.
$get =
$set =
After this lines
$property->setValue($vector, $set);
pre_clear_buffer_die($property->getValue($vector));
i obtain this
I try to put other value like an bool or null inside property and after set the $set but it's not works.
P.S: pre_clear_buffer_die kill php buffer, init other buffer and show var inside a <pre> after exit from script. Is an debugger function.

Send a data from table to another table from a specific source field

Please help me about this one.
i have a table name 'aptimportdata' and 'aptimportdataaddress'.
the code below is a function for import a microsoft excel data to the website.
i want to send a data from table aptimportdata to aptimportdataaddress, but i don't know how, because in the excel file, there are 2 home address columns for one person, one with the columns name homeaddress1 to 4, and the other one is altaddress1 to 4, the "altaddress" is created for a person who have a home address more than 1.
now when i import the data from the website, the data is sent to the aptimportdata table and it doesn't have a problem when i upload the file from the website, but when i change the "altaddress" data destination table to aptimportdataaddress table, the website just give me an endless loading without a success report.
i already make a column for the "altaddress" in aptimportdataaddress table, but i cant find a solution how to make the "altaddress" data go to aptimportaddress table and its just the "altaddress" column data that i want to put at the aptimportdataaddress table.
if you need a screenshot for the what the table looks like, i'll send it.
this is my code :
= 5.3.3
* #copyright 2014 Sereware
* #developer Yudha Tama Aditiyara
* #application controller/apartement
*/
class import extends Controller
{
protected $_models = array('apartement/import/m_import');
public function dataexcel(){
$config['ajax_upload_dataexcel'] = site_url('apartement/import/ajax_upload_dataexcel');
$config['ajax_process_dataexcel'] = site_url('apartement/import/ajax_process_dataexcel/'.$this->d_page->page('noid'));
$this->load->view('apartement/import/dataexcel',$config);
}
public function ajax_upload_dataexcel(){
$id = str_replace('.','',microtime(true));
$upload = new Sereware\ExcelUpload(array('upload_dir' => SYSPATH.'files/'),false);
$upload->hasNormalFilename = true;
$this->d_page->obstart();
$upload->post();
ob_flush();
}
protected $apttower = array(
'h' => 1,'s'=>2,'y'=>3,'p'=>4
);
#{{{
protected function get_dataexcel(){
if (!isset($_REQUEST['file']) || !trim($_REQUEST['file']))return;
$file = $_REQUEST['file'];
$file = SYSPATH."files/" . $file . (pathinfo($file,PATHINFO_EXTENSION) !== 'xls' ? '.xls' : '');
if (!file_exists($file)) return;
$excel = new Sereware\Excel($file);
$data = $excel->getCells(0);
return $data;
}
protected function matcher_excelfield($dataexcelfields, $appimportdetails){
$fieldnames = array();
foreach($dataexcelfields as $indexField => $dataexcelfield) {
$dataexcelfield = strtolower(preg_replace('#[\n\r]#','',trim($dataexcelfield)));
if (isset($appimportdetails[$dataexcelfield])) {
$destfield = preg_replace('#[\n\r]#','',$appimportdetails[$dataexcelfield]->destfield);
$desttypefield = (int)$appimportdetails[$dataexcelfield]->desttypefield;
$isnormalized = $appimportdetails[$dataexcelfield]->isnormalized;
$defaultvalue = $appimportdetails[$dataexcelfield]->defaultvalue;
$appimportdetail = $appimportdetails[$dataexcelfield];
$appimportdetail_desttables = array_filter(explode(';',$appimportdetail->desttable));
foreach($appimportdetail_desttables as $tablename) {
$fieldnames[$tablename][$indexField] = array(
'destfield' => $destfield,
'desttypefield' => $desttypefield,
'isnormalized' => $isnormalized,
'defaultvalue' => $defaultvalue
);
}
}
}
return $fieldnames;
}
protected function normalize_dataexcel($destfield,$value){
$value = trim($value);
switch($destfield) {
case 25:
$value = str_replace('%','',$value);
break;
case 11:
if ($value){
$value = strtotime(str_replace('/', '-',(string)$value));
$value = date('Y-m-d',$value);
} else {
$value = null;
}
break;
case 34:
if (!$value) {
$value = -1;
} else {
$value = strtolower($value) === 'ok' ? 1 : 0;
}
break;
}
return $value;
}
public function ajax_process_dataexcel($idpage){
$appimport = $this->m_import->get_appimport();
$appimportdetails = $this->m_import->get_appimportdetails($appimport->idconnection,$appimport->noid);
$aptimportdatas = $this->m_import->get_aptimportdatas($appimport->idconnection);
$newid_aptimportdata = $this->m_import->get_maxid_aptimportdata();
$aptsyarats = $this->m_import->data_aptsyarats();
$aptdatabap = $this->m_import->data_aptbap();
$dataexcel = $this->get_dataexcel();
$dataexcelfields = $this->matcher_excelfield(array_shift($dataexcel),$appimportdetails);
$insert_data = array();
$update_data = array();
$insert_data_aptunitroom = array();
$insert_data_aptimportdataaddress = array();
$insert_data_aptunitroomsyarat = array();
$insert_data_aptdatabap = array();
$datamcarduser = $this->d_page->d_login->get_datamcarduser();
// var_dump(json_encode($dataexcelfields));
// exit();
foreach($dataexcel as $data) {
foreach($dataexcelfields as $tablename => $fieldnames) {
##-1
##-build data per-row
$ndata = array();
$ready = true;
$ndata['idcreate'] = $datamcarduser->noid;
$ndata['idupdate'] = $datamcarduser->noid;
$ndata['docreate'] = date('Y-m-d H:i:s');
$ndata['lastupdate'] = date('Y-m-d H:i:s');
foreach($fieldnames as $indexFieldExcel => $datafields) {
$fieldname = $datafields['destfield'];
$isnormalized = intval($datafields['isnormalized']);
$defaultvalue = $datafields['defaultvalue'];
$desttypefield = $datafields['desttypefield'];
if (!$isnormalized) {
$defaultvalue = $data[$indexFieldExcel];
}
$ndata[$fieldname] = $this->normalize_dataexcel($desttypefield,$defaultvalue);
}
##-2
if (isset($ndata['lotno']) && isset($aptimportdatas[$ndata['lotno']])) {
$metadata = $aptimportdatas[$ndata['lotno']];
if ($tablename === 'aptimportdata') {
$update_data[$tablename][$metadata['metadata']->noid] = $ndata;
// if (!empty($ndata['ppjbdate'])) {
// }
$update_data['aptunitroom'][$metadata['metadata']->noid] = array(
'statuslegal' => empty($ndata['ppjbdate']) ? 0 : 1,
'statusproject' => $ndata['isreadytoho']
);
$mimportlog_r = array_merge(array("noid" => $metadata['metadata']->noid), $ndata);
$insert_data['mimportlog'][] = $mimportlog_r;
continue;
}
$matchers = $metadata['matchers'];
$extrafields = $metadata['extrafields'];
if (isset($matchers[$tablename])) {
foreach($matchers[$tablename] as $_fieldname => $value) {
if ($value === (int)$ndata[$_fieldname]) {
$ready = false;
break;
}
}
}
##-
if ($ready) {
if (isset($extrafields[$tablename])) {
foreach($extrafields[$tablename] as $__fieldname => $_value) {
$ndata[$__fieldname] = $_value;
}
}
}
}
##-3
if ($ready) {
$lotno = false;
if ($tablename === 'aptimportdata') {
$lotno = $ndata['lotno'];
$ndata['noid'] = $newid_aptimportdata;
$insert_data_aptunitroom[] = array(
'noid' => $newid_aptimportdata,
'statusproject' => $ndata['isreadytoho'],
'statuslegal' => empty($ndata['ppjbdate']) ? -1 : 1
);
$insert_data_aptimportdataaddress[] = array(
'noid' => $newid_aptimportdata
);
foreach($aptsyarats as $key => &$aptsyaratdata) {
$aptsyaratdata = (array)$aptsyaratdata;
$aptsyaratdata['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptunitroomsyarat[] = $aptsyaratdata;
}
foreach($aptdatabap as $key => $data){
$data = (array)$data;
$data['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptdatabap[] = $data;
}
$newid_aptimportdata++;
}
if ($lotno !== false) {
$insert_data[$tablename][$lotno] = $ndata;
} else {
$insert_data[$tablename][] = $ndata;
}
}
}
}
$real_insert_data = array();
if (isset($insert_data['aptimportdata'])) {
$_aptimportdata = $insert_data['aptimportdata'];
$real_insert_data['aptimportdata'] = array_values($_aptimportdata);
$real_insert_data['mimportlog'] = array_values($_aptimportdata);
foreach($insert_data as $tablename => $datas) {
if ($tablename !== 'aptimportdata' && $tablename !== 'aptunitroom') {
$real_insert_data[$tablename] = array();
foreach($datas as $key => $data) {
if ((!isset($data['idaptunitroom']) || intval($data['idaptunitroom']) === 0) || $_aptimportdata[$data['lotno']]) {
$data['idaptunitroom'] = $_aptimportdata[$data['lotno']]['noid'];
}
$real_insert_data[$tablename][$key] = $data;
}
}
}
} else {
$real_insert_data = $insert_data;
}
if (!empty($insert_data_aptunitroom)) {
$real_insert_data['aptunitroom'] = $insert_data_aptunitroom;
$real_insert_data['aptimportdataaddress'] = $insert_data_aptimportdataaddress;
}
if (!empty($insert_data_aptunitroomsyarat)) {
$real_insert_data['aptunitroomsyarat'] = $insert_data_aptunitroomsyarat;
$real_insert_data['aptunitroomdatabap'] = $insert_data_aptdatabap;
}
$gagal = array();
$dbase = new Sereware\Query($appimport->idconnection);
// var_dump(json_encode($real_insert_data));
// exit();
if (!empty($real_insert_data)) {
foreach($real_insert_data as $tablename => $data) {
try {
$db = $dbase->table($tablename);
$db->insert($data);
}catch(Exception $e){
$gagal['insert'][$tablename] = $e->getMessage();
}
}
}
if (!empty($update_data)) {
foreach($update_data as $tablename => $datas) {
foreach($datas as $noid => $data) {
try {
$db = $dbase->table($tablename);
$db->where('noid','=',$noid);
$db->update($data);
}catch(Exception $e){
$gagal['update'][$tablename] = $e->getMessage();
}
}
}
}
ob_start();
echo !count($gagal);
ob_flush();
}
#}}}
}
i'm still using localhost, and sublime text.
the "altaddress" and "homeaddress" are not inside the code, because it's a columns in the table. you can only find a table name on the code.
my question is how can i make the "altaddress" data from aptimportdata table go to aptimportdataaddress table, i dont't want the altaddress go to aptimportdata table, i just want the data get to aptimportdataaddress.

Fatal error: Call to a member function selectCollection() on a non-object in C:\xampp\htdocs\phpmongodb\db.php

Can someone please help me, I get this fatal error message when I try to run the code in a browser. I have searched through various topics and couldn't find the answer. I have two very similar functions and only one of them is reporting an error. Function getById is working just fine, but function get reports an error. Here's my db.php file:
class DB {
private $db;
public $limit = 5;
public function __construct($config){
$this->connect($config);
}
private function connect($config){
try{
if ( !class_exists('Mongo')){
echo ("The MongoDB PECL extension has not been installed or enabled");
return false;
}
$connection= new MongoClient($config['connection_string'],array('username'=>$config['username'],'password'=>$config['password']));
return $this->db = $connection->selectDB($config['dbname']);
}catch(Exception $e) {
return false;
}
}
public function create($collection,$article){
$table = $this->db->selectCollection($collection);
return $result = $table->insert($article);
}
public function get($page,$collection){
$currentPage = $page;
$articlesPerPage = $this->limit;
//number of article to skip from beginning
$skip = ($currentPage - 1) * $articlesPerPage;
$table = $this->db->selectCollection($collection); **//here reports an error**
$cursor = $table->find();
//total number of articles in database
$totalArticles = $cursor->count();
//total number of pages to display
$totalPages = (int) ceil($totalArticles / $articlesPerPage);
$cursor->sort(array('saved_at' => -1))->skip($skip)->limit($articlesPerPage);
//$cursor = iterator_to_array($cursor);
$data=array($currentPage,$totalPages,$cursor);
return $data;
}
public function getById($id,$collection){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new MongoId($id);
}
$table = $this->db->selectCollection($collection);
$cursor = $table->find(array('_id' => $id));
$article = $cursor->getNext();
if (!$article ){
return false ;
}
return $article;
}
public function delete($id,$collection){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new \MongoId($id);
}
$table = $this->db->selectCollection($collection);
$result = $table->remove(array('_id'=>$id));
if (!$id){
return false;
}
return $result;
}
public function update($id,$collection,$article){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new \MongoId($id);
}
$table = $this->db->selectCollection($collection);
$result = $table->update(
array('_id' => new \MongoId($id)),
array('$set' => $article)
);
if (!$id){
return false;
}
return $result;
}
public function commentId($id,$collection,$comment){
$postCollection = $this->db->selectCollection($collection);
$post = $postCollection->findOne(array('_id' => new \MongoId($id)));
if (isset($post['comments'])) {
$comments = $post['comments'];
}else{
$comments = array();
}
array_push($comments, $comment);
return $postCollection->update(
array('_id' => new \MongoId($id)),
array('$set' => array('comments' => $comments))
);
}
}

No refresh register form [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have created a registration form and it works my only issues is I want to be able to hide the post info in the url if you click submit and the validation fails it does this
register.php?action=signup
is there a mod rewrite for this?
so that the url remains
register.php
removing the ?action=signup
I have searched every where but have came up with nothing
php code for register page
<?php
//Error reporting #1-8F636958
error_reporting(E_ALL | E_STRICT);
//End Error reporting
//Include Common Files #1-EDC1CE42
define("RelativePath", ".");
define("PathToCurrentPage", "/");
define("FileName", "NewPage1.php");
include_once(RelativePath . "/Common.php");
include_once(RelativePath . "/Template.php");
include_once(RelativePath . "/Sorter.php");
include_once(RelativePath . "/Navigator.php");
//End Include Common Files
class clsRecordusers { //users Class #2-9BE1AF6F
//Variables #2-9E315808
// Public variables
public $ComponentType = "Record";
public $ComponentName;
public $Parent;
public $HTMLFormAction;
public $PressedButton;
public $Errors;
public $ErrorBlock;
public $FormSubmitted;
public $FormEnctype;
public $Visible;
public $IsEmpty;
public $CCSEvents = "";
public $CCSEventResult;
public $RelativePath = "";
public $InsertAllowed = false;
public $UpdateAllowed = false;
public $DeleteAllowed = false;
public $ReadAllowed = false;
public $EditMode = false;
public $ds;
public $DataSource;
public $ValidatingControls;
public $Controls;
public $Attributes;
// Class variables
//End Variables
//Class_Initialize Event #2-627C035C
function clsRecordusers($RelativePath, & $Parent)
{
global $FileName;
global $CCSLocales;
global $DefaultDateFormat;
$this->Visible = true;
$this->Parent = & $Parent;
$this->RelativePath = $RelativePath;
$this->Errors = new clsErrors();
$this->ErrorBlock = "Record users/Error";
$this->DataSource = new clsusersDataSource($this);
$this->ds = & $this->DataSource;
$this->InsertAllowed = true;
if($this->Visible)
{
$this->ComponentName = "users";
$this->Attributes = new clsAttributes($this->ComponentName . ":");
$CCSForm = explode(":", CCGetFromGet("ccsForm", ""), 2);
if(sizeof($CCSForm) == 1)
$CCSForm[1] = "";
list($FormName, $FormMethod) = $CCSForm;
$this->EditMode = ($FormMethod == "Edit");
$this->FormEnctype = "application/x-www-form-urlencoded";
$this->FormSubmitted = ($FormName == $this->ComponentName);
$Method = $this->FormSubmitted ? ccsPost : ccsGet;
$this->btn_register = new clsButton("btn_register", $Method, $this);
$this->username = new clsControl(ccsTextBox, "username", "Soldier", ccsText, "", CCGetRequestParam("username", $Method, NULL), $this);
$this->username->Required = true;
$this->user_email = new clsControl(ccsTextBox, "user_email", "User Email", ccsText, "", CCGetRequestParam("user_email", $Method, NULL), $this);
$this->user_email->Required = true;
$this->user_birthdate = new clsControl(ccsTextBox, "user_birthdate", "User Birthdate", ccsText, "", CCGetRequestParam("user_birthdate", $Method, NULL), $this);
$this->user_birthdate->Required = true;
}
}
//End Class_Initialize Event
//Initialize Method #2-052CBF13
function Initialize()
{
if(!$this->Visible)
return;
$this->DataSource->Parameters["urluid"] = CCGetFromGet("uid", NULL);
}
//End Initialize Method
//Validate Method #2-B7C6592D
function Validate()
{
global $CCSLocales;
$Validation = true;
$Where = "";
$Validation = ($this->username->Validate() && $Validation);
$Validation = ($this->user_email->Validate() && $Validation);
$Validation = ($this->user_birthdate->Validate() && $Validation);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "OnValidate", $this);
$Validation = $Validation && ($this->username->Errors->Count() == 0);
$Validation = $Validation && ($this->user_email->Errors->Count() == 0);
$Validation = $Validation && ($this->user_birthdate->Errors->Count() == 0);
return (($this->Errors->Count() == 0) && $Validation);
}
//End Validate Method
//CheckErrors Method #2-E8847328
function CheckErrors()
{
$errors = false;
$errors = ($errors || $this->username->Errors->Count());
$errors = ($errors || $this->user_email->Errors->Count());
$errors = ($errors || $this->user_birthdate->Errors->Count());
$errors = ($errors || $this->Errors->Count());
$errors = ($errors || $this->DataSource->Errors->Count());
return $errors;
}
//End CheckErrors Method
//Operation Method #2-6BA9892D
function Operation()
{
if(!$this->Visible)
return;
global $Redirect;
global $FileName;
$this->DataSource->Prepare();
if(!$this->FormSubmitted) {
$this->EditMode = $this->DataSource->AllParametersSet;
return;
}
if($this->FormSubmitted) {
$this->PressedButton = "btn_register";
if($this->btn_register->Pressed) {
$this->PressedButton = "btn_register";
}
}
$Redirect = $FileName . "?" . CCGetQueryString("QueryString", array("ccsForm"));
if($this->Validate()) {
if($this->PressedButton == "btn_register") {
if(!CCGetEvent($this->btn_register->CCSEvents, "OnClick", $this->btn_register) || !$this->InsertRow()) {
$Redirect = "";
}
}
} else {
$Redirect = "";
}
if ($Redirect)
$this->DataSource->close();
}
//End Operation Method
//InsertRow Method #2-C62BC29D
function InsertRow()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeInsert", $this);
if(!$this->InsertAllowed) return false;
$this->DataSource->username->SetValue($this->username->GetValue(true));
$this->DataSource->user_email->SetValue($this->user_email->GetValue(true));
$this->DataSource->user_birthdate->SetValue($this->user_birthdate->GetValue(true));
$this->DataSource->Insert();
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterInsert", $this);
return (!$this->CheckErrors());
}
//End InsertRow Method
//Show Method #2-AE9867B3
function Show()
{
global $CCSUseAmp;
$Tpl = CCGetTemplate($this);
global $FileName;
global $CCSLocales;
$Error = "";
if(!$this->Visible)
return;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeSelect", $this);
$RecordBlock = "Record " . $this->ComponentName;
$ParentPath = $Tpl->block_path;
$Tpl->block_path = $ParentPath . "/" . $RecordBlock;
$this->EditMode = $this->EditMode && $this->ReadAllowed;
if($this->EditMode) {
if($this->DataSource->Errors->Count()){
$this->Errors->AddErrors($this->DataSource->Errors);
$this->DataSource->Errors->clear();
}
$this->DataSource->Open();
if($this->DataSource->Errors->Count() == 0 && $this->DataSource->next_record()) {
$this->DataSource->SetValues();
if(!$this->FormSubmitted){
$this->username->SetValue($this->DataSource->username->GetValue());
$this->user_email->SetValue($this->DataSource->user_email->GetValue());
$this->user_birthdate->SetValue($this->DataSource->user_birthdate->GetValue());
}
} else {
$this->EditMode = false;
}
}
if($this->FormSubmitted || $this->CheckErrors()) {
$Error = "";
$Error = ComposeStrings($Error, $this->username->Errors->ToString());
$Error = ComposeStrings($Error, $this->user_email->Errors->ToString());
$Error = ComposeStrings($Error, $this->user_birthdate->Errors->ToString());
$Error = ComposeStrings($Error, $this->Errors->ToString());
$Error = ComposeStrings($Error, $this->DataSource->Errors->ToString());
$Tpl->SetVar("Error", $Error);
$Tpl->Parse("Error", false);
}
$CCSForm = $this->EditMode ? $this->ComponentName . ":" . "Edit" : $this->ComponentName;
$this->HTMLFormAction = $FileName . "?" . CCAddParam(CCGetQueryString("QueryString", ""), "ccsForm", $CCSForm);
$Tpl->SetVar("Action", !$CCSUseAmp ? $this->HTMLFormAction : str_replace("&", "&", $this->HTMLFormAction));
$Tpl->SetVar("HTMLFormName", $this->ComponentName);
$Tpl->SetVar("HTMLFormEnctype", $this->FormEnctype);
$this->btn_register->Visible = !$this->EditMode && $this->InsertAllowed;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeShow", $this);
$this->Attributes->Show();
if(!$this->Visible) {
$Tpl->block_path = $ParentPath;
return;
}
$this->btn_register->Show();
$this->username->Show();
$this->user_email->Show();
$this->user_birthdate->Show();
$Tpl->parse();
$Tpl->block_path = $ParentPath;
$this->DataSource->close();
}
//End Show Method
} //End users Class #2-FCB6E20C
class clsusersDataSource extends clsDBlocalhost { //usersDataSource Class #2-5EDEDCFF
//DataSource Variables #2-8A9D7D42
public $Parent = "";
public $CCSEvents = "";
public $CCSEventResult;
public $ErrorBlock;
public $CmdExecution;
public $InsertParameters;
public $wp;
public $AllParametersSet;
public $InsertFields = array();
// Datasource fields
public $username;
public $user_email;
public $user_birthdate;
//End DataSource Variables
//DataSourceClass_Initialize Event #2-56B8B1F7
function clsusersDataSource(& $Parent)
{
$this->Parent = & $Parent;
$this->ErrorBlock = "Record users/Error";
$this->Initialize();
$this->username = new clsField("username", ccsText, "");
$this->user_email = new clsField("user_email", ccsText, "");
$this->user_birthdate = new clsField("user_birthdate", ccsText, "");
$this->InsertFields["soldier"] = array("Name" => "soldier", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
$this->InsertFields["user_email"] = array("Name" => "user_email", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
$this->InsertFields["user_birthdate"] = array("Name" => "user_birthdate", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
}
//End DataSourceClass_Initialize Event
//Prepare Method #2-DC2F5FB8
function Prepare()
{
global $CCSLocales;
global $DefaultDateFormat;
$this->wp = new clsSQLParameters($this->ErrorBlock);
$this->wp->AddParameter("1", "urluid", ccsInteger, "", "", $this->Parameters["urluid"], "", false);
$this->AllParametersSet = $this->wp->AllParamsSet();
$this->wp->Criterion[1] = $this->wp->Operation(opEqual, "uid", $this->wp->GetDBValue("1"), $this->ToSQL($this->wp->GetDBValue("1"), ccsInteger),false);
$this->Where =
$this->wp->Criterion[1];
}
//End Prepare Method
//Open Method #2-B071412E
function Open()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildSelect", $this->Parent);
$this->SQL = "SELECT * \n\n" .
"FROM users {SQL_Where} {SQL_OrderBy}";
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteSelect", $this->Parent);
$this->query(CCBuildSQL($this->SQL, $this->Where, $this->Order));
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteSelect", $this->Parent);
}
//End Open Method
//SetValues Method #2-1C83BB75
function SetValues()
{
$this->username->SetDBValue($this->f("soldier"));
$this->user_email->SetDBValue($this->f("user_email"));
$this->user_birthdate->SetDBValue($this->f("user_birthdate"));
}
//End SetValues Method
//Insert Method #2-D2F97CD9
function Insert()
{
global $CCSLocales;
global $DefaultDateFormat;
$this->CmdExecution = true;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildInsert", $this->Parent);
$this->InsertFields["soldier"]["Value"] = $this->username->GetDBValue(true);
$this->InsertFields["user_email"]["Value"] = $this->user_email->GetDBValue(true);
$this->InsertFields["user_birthdate"]["Value"] = $this->user_birthdate->GetDBValue(true);
$this->SQL = CCBuildInsert("users", $this->InsertFields, $this);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteInsert", $this->Parent);
if($this->Errors->Count() == 0 && $this->CmdExecution) {
$this->query($this->SQL);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteInsert", $this->Parent);
}
}
//End Insert Method
} //End usersDataSource Class #2-FCB6E20C
//Initialize Page #1-2A4101A9
// Variables
$FileName = "";
$Redirect = "";
$Tpl = "";
$TemplateFileName = "";
$BlockToParse = "";
$ComponentName = "";
$Attributes = "";
// Events;
$CCSEvents = "";
$CCSEventResult = "";
$TemplateSource = "";
$FileName = FileName;
$Redirect = "";
$TemplateFileName = "NewPage1.html";
$BlockToParse = "main";
$TemplateEncoding = "UTF-8";
$ContentType = "text/html";
$PathToRoot = "./";
$PathToRootOpt = "";
$Scripts = "|";
$Charset = $Charset ? $Charset : "utf-8";
//End Initialize Page
//Before Initialize #1-E870CEBC
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeInitialize", $MainPage);
//End Before Initialize
//Initialize Objects #1-1F103AC9
$DBlocalhost = new clsDBlocalhost();
$MainPage->Connections["localhost"] = & $DBlocalhost;
$Attributes = new clsAttributes("page:");
$Attributes->SetValue("pathToRoot", $PathToRoot);
$MainPage->Attributes = & $Attributes;
// Controls
$users = new clsRecordusers("", $MainPage);
$MainPage->users = & $users;
$users->Initialize();
$ScriptIncludes = "";
$SList = explode("|", $Scripts);
foreach ($SList as $Script) {
if ($Script != "") $ScriptIncludes = $ScriptIncludes . "<script src=\"" . $PathToRoot . $Script . "\" type=\"text/javascript\"></script>\n";
}
$Attributes->SetValue("scriptIncludes", $ScriptIncludes);
$CCSEventResult = CCGetEvent($CCSEvents, "AfterInitialize", $MainPage);
if ($Charset) {
header("Content-Type: " . $ContentType . "; charset=" . $Charset);
} else {
header("Content-Type: " . $ContentType);
}
//End Initialize Objects
//Initialize HTML Template #1-28F2FDD6
$CCSEventResult = CCGetEvent($CCSEvents, "OnInitializeView", $MainPage);
$Tpl = new clsTemplate($FileEncoding, $TemplateEncoding);
if (strlen($TemplateSource)) {
$Tpl->LoadTemplateFromStr($TemplateSource, $BlockToParse, "UTF-8");
} else {
$Tpl->LoadTemplate(PathToCurrentPage . $TemplateFileName, $BlockToParse, "UTF-8");
}
$Tpl->SetVar("CCS_PathToRoot", $PathToRoot);
$Tpl->block_path = "/$BlockToParse";
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeShow", $MainPage);
$Attributes->SetValue("pathToRoot", "");
$Attributes->Show();
//End Initialize HTML Template
//Execute Components #1-0C9864E9
$users->Operation();
//End Execute Components
//Go to destination page #1-810C207B
if($Redirect)
{
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeUnload", $MainPage);
$DBlocalhost->close();
header("Location: " . $Redirect);
unset($users);
unset($Tpl);
exit;
}
//End Go to destination page
//Show Page #1-E3A8594F
$users->Show();
$Tpl->block_path = "";
$Tpl->Parse($BlockToParse, false);
if (!isset($main_block)) $main_block = $Tpl->GetVar($BlockToParse);
$main_block = CCConvertEncoding($main_block, $FileEncoding, $TemplateEncoding);
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeOutput", $MainPage);
if ($CCSEventResult) echo $main_block;
//End Show Page
//Unload Page #1-4215F8E1
$CCSEventResult = CCGetEvent ($CCSEvents, "BeforeUnload", $MainPage);
$DBlocalhost->close();
unset($users);
unset($Tpl);
//End Unload Page
?>
You can submit the information via POST. The way you are submitting the data across is from a GET HTTP request. The best thing to do is submit it over via post data. I am assuming your frontend call is using ajax for the form submission? if not and using a simple form change method to POST. If it is using ajax, I would need to know if you are using something like jquery or crafting the XHR request yourself, but if you are doing it that way I would assume you would know the difference.
<form action="action_page.php" method="POST">

Categories