How to insert table from database employee to my template document as above?
I successfully filled company field.
code like bellow
require_once APPPATH.'libraries/autoload.php';
use PhpOffice\PhpWord\PhpWord;
public function cetaksurat()
{
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('source.docx');
$templateProcessor->setValues([
'company' => 'my company',
//how to insert employee table from my database array result?
//.....
]);
header("Content-Disposition: attachment; filename=result.docx");
$templateProcessor->saveAs('php://output');
}
thank you
in my case I would use:
$news2 = $this->phpword_model->get_employe(); //
foreach($news2 as $key=>$values) {
$array_values1 = $values['id'];
$array_values2 = $values['name'];
}
$templateProcessor->setValue('id', $array_values1);
$templateProcessor->setValue('name', $array_values2);
$templateProcessor->saveAs($filename);
/// the first example is for a single record.
now this example is for multiple records.
$news7 = $this->phpword_model->get_employes();
$templateProcessor->cloneRow('id', count($news7));
$i=1;
foreach($news7 as $key=>$values) {
$templateProcessor->setValue('id#'.$i++, $values['id']);
}
$i2=1;
foreach($news7 as $key=>$values) {
$templateProcessor->setValue('name#'.$i2++, $values['name']);
}
$templateProcessor->saveAs($filename);
Related
Hi I have a project and trying to save the data that is being loop. And I am using codeigniter as framework on PHP. And I am not able to save the data on the Loop statement.
Here is my model:
$tdl ='';
$append = 'insert into collateral3 (clientId, resAreatdl, resNumtdl, resValasstdl, resYearasstdl, comAreatdl, comNumtdl, comAssvaltdl, comYearasstdl, agriAreatdl, agriNumtdl, agriAssvaltdl, agriYearasstdl) values ';
if (array_key_exists('tdl', $info)) {
foreach($info['tdl'] as $row) {
if (!empty($row['resAreatdl'])) {
$tdl .= $append ."('$clientId', upper('{$row['resAreatdl']}'), upper('{$row['resNumtdl']}'), upper('{$row['resAssvaltdl']}'), upper('{$row['resYearasstdl']}'), upper('{$row['comAreatdl']}'), upper('{$row['comNumtdl']}'), upper('{$row['comAssvaltdl']}'), upper('{$row['comYearasstdl']}'), upper('{$row['agriAreatdl']}'), upper('{$row['agriNumtdl']}'), upper('{$row['agriAssvaltdl']}'), upper('{$row['agriYearasstdl']}'))";
}
$append =", ";
}
}
For more than one record use batch insert
if (array_key_exists('tdl', $info)) {
foreach($info['tdl'] as $row) {
$data[] = array(
'clientId' => $clientId ,
'resAreatdl' => $row['resAreatdl'],
'resNumtdl' => $row['resNumtdl']
/* add your all field like this*/
);
}
}
$this->db->insert_batch('collateral3', $data);
I need to upload an excel file and import the content in the database to the related table.
I have already created a script to import it. The script below works properly
$excelObj = $this->get('phpexcel')->createPHPExcelObject($path_file);
$sheet = $excelObj->getActiveSheet()->toArray(null,true,true,true);
$em = $this->getDoctrine()->getManager();
//READ EXCEL FILE CONTENT
foreach($sheet as $i=>$row) {
if($i !== 1) {
$account = $em->getRepository('ExcelBundle:Users')->findOneByUsername($row['A']);
if(!$account) {
$user = new Users();
}
$user->setName($row['A']);
$user->setUsername($row['B']);
$user->setEmail($row['C']);
//... and so on
$em->persist($user);
$em->flush();
}
}
Now, instead of importing the row A, row B...etc of the excel file I need to import the name of the row.
name username email ...and so on
$user->setName($row['name']);
$user->setUsername($row['username']);
$user->setEmail($row['email']);
How can I do it?
So you need to map the headings row (row #1) to the actual values in each subsequent row
foreach($sheet as $i=>$row) {
if($i == 1) {
$headings = $row;
} else {
$row = array_combine($headings, $row);
.... do the rest of your stuff here
$user->setName($row['name']);
$user->setUsername($row['username']);
$user->setEmail($row['email']);
....
}
I am build uploader images and store it into database, I already can upload many images to folder, but I can't insert all images name that uploaded, and I don't know how to insert into database, first I have put commend on my code below when error occur, second I don't know the query to put it in database if the image count is different e.g 1-10 images, last question, if I do query "SELECT id..." and I want to return it, is there method to return it into string or int? If I use row() it will return stdClass object. please help me,
below is my code:
controller :
$this->load->library("myupload", "form_validation");
$this->load->model("testModel");
$barangImage = array();
if($this->input->post("formSubmit")) {
$this->form_validation->set_rules("nama", "Nama", "required|trim");
if($this->form_validation->run()) {
$insertData = array(
"nama" => $this->input->post("nama")
);
if($id = $this->testModel->add($insertData)) {
//print_r($id);
if(isset($_FILES) && $image = $this->myupload->uploadFile($_FILES)) {
//$image here is already fill with all images name
if(isset($image["error"]) && $image["error"]) {
echo $image["error"];
}else {
foreach($image as $img) {
$barangImage = array(
"gambar" => $img,
"barangid" => $id
);
}
//but when i put into barangImage,
//it only stored last image name
print_r($barangImage);
//output `Array ( [gambar] => 2.JPG [barangid] => Array ( [id] => 52 ) )`
}
}
if($id = $this->testModel->add_images($barangImage)) {
echo "SUCCESS !!!";
}else {
echo "FAIL INSERT IMAGES!!!";
}
}else {
echo "FAIL INSERT DATA NAMA";
}
}else {
echo "FAIL VALIDASI RUN";
}
}
model :
public function add($newData){
$this->db->insert("cobabarang", $newData);
$nama = $newData["nama"];
$id = $this->db->query("SELECT id FROM cobabarang WHERE nama = \"$nama\"");
return $id->row_array();
}
public function add_images($newImage) {
//$this->db->insert("cobagambar", $newImage);
$id = $newImage["barangid"]["id"];
$gambar = $newImage["gambar"];
$this->db->query("INSERT INTO cobagambar(barangid, gambar1) VALUES($id, \"$gambar\")");
}
there is an error here:
foreach($image as $img)
{
$barangImage = array(
"gambar" => $img,
"barangid" => $id
);
}
change the $barangImage to $barangImage[]
when you put the images into database i suggest that using json_encode($barangImage), and then json_decode($images-json-string) when you going to use the images.
There is something wrong with your foreach loop
foreach($image as $img) {
$barangImage = array(
"gambar" => $img //might be img['img'] I guess $img is again an array...you hvae to check that
"barangid" => $id //might be $img['id']check on this too..will be $img['id'] I guess
);
}
My guess is that $img is again an array with some keys. You really need to check on that And you can directly call the insert function in that foreach loop itself like this,
foreach($image as $img) {
$barangImage = array(
"gambar1" => $img['img'], //I guess $img is again an array...you hvae to check that
"barangid" => $img['id'] //check on this too..will be $img['id'] I guess
);
$id = $this->testModel->add_images($barangImage));
}
NOTE: The keys in your array barangImage must be column name in the table. i.e
gambar1 and barangid will be your column names. so you can directly use codeIgniter's active records.
Just change your add_images function
public function add_images($newImage) {
$this->db->insert("cobagambar", $newImage);
}
I am trying save batch record from form and save to database.
I got sample from Advanced Example it is a widgets. this. example only add record without save it I add a save bottom under widget and form top of widget. add code for add or update ,I add id filed in widget . records read from database .
when I update record i have not any problem but when I add record my program don't save new record i trace program and see $_post[model] include old record and have not new record . when I element id field from from . all record re-save I left program
pic1 pic2
_form_batch.php
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'person-form',
'enableAjaxValidation'=>true,
'enableClientValidation' => true,
)); ?>
<h2><?php
$persons2=Person::model()->findAll();
echo Help::item('annotation','title',!Yii::app()->user->isGuest); ?></h2>
<div class="large-text"><?php echo Help::item('annotation','content'); ?></div>sas
<?php $this->widget('ext.widgets.tabularinput.XTabularInput',array(
'models'=>$persons2,
'containerTagName'=>'table',
'headerTagName'=>'thead',
'header'=>'
<tr>
<td>'.CHtml::activeLabelEX(Person::model(),'id').'</td>
<td>'.CHtml::activeLabelEX(Person::model(),'firstname').'</td>
<td>'.CHtml::activeLabelEX(Person::model(),'lastname').'</td>
<td>'.CHtml::activeLabelEX(Person::model(),'country_id').'</td>
<td>'.CHtml::activeLabelEX(Person::model(),'eyecolor_code').'</td>
<td>'.CHtml::activeLabelEX(Person::model(),'email').'</td>
<td></td>
</tr>
',
'inputContainerTagName'=>'tbody',
'inputTagName'=>'tr',
'inputView'=>'extensions/_tabularInputAsTable',
'inputUrl'=>$this->createUrl('request/addTabularInputsAsTable2'),
'addTemplate'=>'<tbody><tr><td colspan="6">{link}</td></tr></tbody>',
'addLabel'=>Yii::t('ui','Add new row'),
'addHtmlOptions'=>array('class'=>'blue pill full-width'),
'removeTemplate'=>'<td>{link}</td>',
'removeLabel'=>Yii::t('ui','Delete'),
'removeHtmlOptions'=>array('class'=>'red pill'),
)); ?>
<div class="action">
<?php echo CHtml::submitButton($model->isNewRecord ? Yii::t('ui', 'Create') : Yii::t('ui','Save'),array('class'=>'btn btn-primary')); ?>
<?php echo CHtml::link(Yii::t('ui', 'Cancel'), $model->isNewRecord ? array('admin') : $this->getReturnUrl(), array('class'=>'btn')) ?>
</div>
<?php $this->endWidget(); ?>
controller:
$person = new Person;
$persons = $this->getItemsToUpdate();
// print_r($_POST); exit;
if (isset($_POST['Person'])) {
$valid = true;
foreach ($persons as $i => $person) {
if (isset($_POST['Person'][$i]))
$person->attributes = $_POST['Person'][$i];
$valid = $person->validate() && $valid;
print_r($_POST['Person'][$i]);
$person->save();
$errores = $person->getErrors();
// print_r($errores);
// echo " valid: " . $valid . "<br>";
}
}
$this->render('hame', array(
'model' => $persons,
));
}
public function getItemsToUpdate() {
// Create an empty list of records
$persons = array();
print_r($_POST['Person']);
// Iterate over each item from the submitted form
if (isset($_POST['Person']) && is_array($_POST['Person'])) {
foreach ($_POST['Person'] as $person) {
// If item id is available, read the record from database
if (array_key_exists('id', $person)) {
$persons[] = Person::model()->findByPk($person['id']);
}
// Otherwise create a new record
else {
$persons[] = new Person();
}
}
}
return $persons;
}
first point is:
**$person** = new Person;
foreach ($persons as $i => **$person**) {
second is:
i had some problems with foreach and save, better use
$cmd = Yii::app()->db->createCommand();
$cmd->insert(...
$cmd->update(...
otherwise you have to create new model on each iteration and than use save()
I need to run forloop in yii model action create or Addipblock() and save every record although forloop end and then redirect it to view admin,
My first record take start from 1 and end 50, So in database should be 50 records added.
My code is like this:
`public function actionAddipblock(){
$model=new IpManager('addipblock');
if(isset($_POST['IpManager'])){
$model->attributes=$_POST['IpManager'];
$starting_ip = $_POST['IpManager']['starting_ip'];
$ending_ip = $_POST['IpManager']['ending_ip'];
if($model->validate('addipblock')){
for($ip = $starting_ip; $ip <= $ending_ip; $ip++){
$model->ip = $ip;
$model->server = $_POST['IpManager']['server'];
$model->client = $_POST['IpManager']['client'];
$model->status = $_POST['IpManager']['status'];
$model->creation_date = date("Y-m-d H:i:s");
}
if($model->save()){
$this->redirect(array('admin'));
}
else{
echo 'Error:';
}
}
}
$this->render('addipblock',array('model'=>$model));
}`
But when I run this code it save only one record not save all recorde until forloop end.
Guys what will you suggest me for this? what should I can do for this?
Try this inside you forloop,
for($ip = $starting_ip; $ip <= $ending_ip; $ip++){
// you need to null your model primary key
$model->id = null; // like this
$model->ip = $ip;
$model->server = $_POST['IpManager']['server'];
$model->client = $_POST['IpManager']['client'];
$model->status = $_POST['IpManager']['status'];
$model->creation_date = date("Y-m-d H:i:s");
$model->isNewRecord = true;
$model->save();
}