Foreach loop problem in model using Codeigniter - codeigniter-3

Model:
public function fetch_emp()
{
$this->db->select('emp_id');
$this->db->from('emp');
$res=$this->db->get();
foreach($res->result() as $row)
{
$id=$row->emp_id;
$this->db->select('emp_name');
$this->db->from('employee_master');
$this->db->where('emp_id',$id);
$res=$this->db->get();
return $res->result();
}
}
Controller:
public function employee()
{
$result=$this->emp_model->fetch_emp();
if($result!=false)
$res['cmp_name']=$result;
else
$res['cmp_name']='NA';
}
$this->loadViews("emp/emp_views", $this->global, $res , NULL);
}
View:
<?php print_r($cmp_name);?>
Once I fetch the id from db I got all the id not problem at all, but when I used in foreach loop to search the id and get their names from another db It display only the 1st id name... For eg:If there are 5 id, but when I search the id to get the name from another db it shows the 1st id name only.What's the problem I don't know pls help me.

You could get it done (getting names list) by directly using join() method like this :
public function fetch_emp()
{
$this->db->select('emp_name');
$this->db->from('emp');
$this->db->join('employee_master', 'employee_master.emp_id = emp.emp_id');
$res=$this->db->get();
return $res->result();
}

Related

Get last insert id in store function

How to get the last insert id in backpack for laravel 4 in the store function?
public function store()
{
$response = $this->traitStore();
//need the last id for operations
return $response;
}
This code doesn't work for me:
$id = $this->crud->entry->id; // <-- SHOULD WORK
You should have the last inserted item available as $this->data['entry'], so you should be able to get the ID using $this->data['entry']->id

database query according to file input empty or not in codeigniter

So i am changing my project from core PHP to Codeigniter. I have a edit for in which their are 3 input type file. Now i want to run my query according to these inout file. like if input file 1 is empty than don't update value else update. I did it in core PHP like this:
The name of input type file are: image1, image2, image3
mysqli query in core PHP:
if(!empty($photo1))
{
$p1=str_replace("-","",time().$photo1);
move_uploaded_file($_FILES['photo1']['tmp_name'], $folder.$p1);
$query .=",`image1`='$p1'";
}
if(!empty($photo2))
{
$p2=str_replace("-","",time().$photo2);
move_uploaded_file($_FILES['photo2']['tmp_name'], $folder.$p2);
$query .=",`image2`='$p2'";
}
if(!empty($photo3))
{
$p3=str_replace("-","",time().$photo3);
move_uploaded_file($_FILES['photo3']['tmp_name'], $folder.$p3);
$query .=",`image3`='$p3'";
}
Now how to do this in codeigniter model:
controller
public function store_ad()
{
$id=$this->input->post('id');
$d_email=$this->session->userdata('dealer_email');
$p_type=$this->input->post('property_type');
$p_subtype=$this->input->post('property_subtype');
$p_for=$this->input->post('p_for');
$p_name=$this->input->post('p_name');
$p_price=$this->input->post('p_price');
$state=$this->input->post('state');
$city=$this->input->post('city');
$loc=$this->input->post('location');
$pincode=$this->input->post('pincode');
$about=$this->input->post('p_about');
$stat=$this->input->post('status');
$config['upload_path'] = './images/properties';
$config['allowed_types']='gif|png|jpeg|jpg';
$this->load->library('upload',$config);
if($this->upload->do_upload('image1'))
{
$data1=$this->upload->data();
$img1=$data1['raw_name'].$data1['file_ext'];
}
if($this->upload->do_upload('image2'))
{
$data2=$this->upload->data();
$img2=$data2['raw_name'].$data2['file_ext'];
}
if($this->upload->do_upload('image3'))
{
$data3=$this->upload->data();
$img3=$data3['raw_name'].$data3['file_ext'];
}
}
How to crearte model according to the non empty input file. I am storing the name of the file in database
Inside your method in the model class check if the files you want to upload is empty or not e.g
public function update($data_array, $img1, $img2, $img3){
if(!empty($img1)){
$data_array['img_column1'] = $img1;
}
if(!empty($img2)){
$data_array['img_column2'] = $img2;
}
if(!empty($img3)){
$data_array['img_column3'] = $img3;
}
return $this->db->insert('YOUR_TABLE_NAME', $data_array);
}
Hope this helps....

Zend Db query to select all IDs

How would I write an Zend DB query to select all from the column ID?
So far I have tried:
public function getLatestUserID()
{
$ids = $this->select()
->where('id = ?');
return $ids;
}
But to no avail.
You just want the id column,
You failed to call an execute command.
try:
//assuming you are using a DbTable model
public function getLatestUserID()
{
$ids = $this->fetchAll('id');
return $ids;
}
I would do it like this, because I use the select() object for everything:
public function getLatestUserID()
{
$select = $this->select();
//I'm not sure if $this will work in this contex but you can out the table name
$select->from(array($this), array('id'));
$ids = $this->fetchAll($select);
return $ids;
}
The first two examples should return just the id column of the table, now if you actually want to query for a specific id:
public function getLatestUserID($id)
{
$select = $this->select();
$select->where('id = ?', $id);
//fetchAll() would still work here if we wanted multiple rows returned
//but fetchRow() for one row and fetchRowset() for multiple rows are probably
//more specific for this purpose.
$ids = $this->fetchRow($select);
return $ids;
}
make sure your class containing getLatestUserID does extend Zend_Db_Table_Abstract also :
$ids = $this->select()->where('id = ?'); can't work because where('id = ?'); expects an id value like where('id = ?', $id);
if what you want is the latest inserted row's Id use :
$lastInsertId = $this->getAdapter()->lastInsertId();
(however if you are using an oracle database this will not work and you should use $lastInsertId = $this->getAdapter()->lastSequenceId('USER_TABLE_SEQUENCE'); )

Symfony: exclude empty values from form save

I have a many to many relation between Product and Properties. I'm using embedRelation() in my Product form to edit a Product and it's Properties. Properties includes images which causes my issue. Every time I save the form the updated_at column is updated for file properties even when no file is uploaded.
Therefore, I want to exclude empty properties when saving my form.
I'm using Symfony 1.4 and Doctrine 1.2.
I'm thinking something like this in my ProductForm.class.php, but I need some input on how to make this work.
Thanks
class ProductForm extends BaseProductForm
{
public function configure()
{
unset($this['created_at'], $this['updated_at'], $this['id'], $this['slug']);
$this->embedRelation('ProductProperties');
}
public function saveEmbeddedForms($con = null, $forms = null)
{
if (null === $forms)
{
$properties = $this->getValue('ProductProperties');
$forms = $this->embeddedForms;
foreach($properties as $p)
{
// If property value is empty, unset from $forms['ProductProperties']
}
}
}
}
I ended up avoiding Symfony's forms and saving models instead of saving forms. It can be easier when playing with embedded forms. http://arialdomartini.wordpress.com/2011/04/01/how-to-kill-symfony%E2%80%99s-forms-and-live-well/
Solved it by checking if posted value is a file, and if both filename and value_delete is null I unset from the array. It might not be best practice, but it works for now.
Solution based on http://www.symfony-project.org/more-with-symfony/1_4/en/06-Advanced-Forms
class ProductPropertyValidatorSchema extends sfValidatorSchema
{
protected function configure($options = array(), $messages = array())
{
// N0thing to configure
}
protected function doClean($values)
{
$errorSchema = new sfValidatorErrorSchema($this);
foreach($values as $key => $value)
{
$errorSchemaLocal = new sfValidatorErrorSchema($this);
if(array_key_exists('value_delete', $values))
{
if(!$value && !$values['value_delete'])
{
unset($values[$key]);
}
}
// Some error for this embedded-form
if (count($errorSchemaLocal))
{
$errorSchema->addError($errorSchemaLocal, (string) $key);
}
}
// Throws the error for the main form
if (count($errorSchema))
{
throw new sfValidatorErrorSchema($this, $errorSchema);
}
return $values;
}
}

Symfony form with doctrine table other than getTable()->find() is not working

I get a really anoying error when I try to edit an entry from a table, in tutorial they always use getTable()->find(), but I need to verify that the person logged in is the owner of that entry here what I did:
In the action:
public function executeEdit(sfWebRequest $request)
{
$id = $request->getParameter('id');
$userid = $this->getUser()->getGuardUser()->getId();
$ad = Doctrine_Core::getTable('BambinbazarArticles')->getMyAd($id, $userid);
$this->forward404Unless($ad, sprintf('Object bambinbazar_articles does not exist (%s).', $request->getParameter('id')));
$this->form = new BambinbazarArticlesForm($ad);
}
In the model:
public function getMyAd($id, $userid)
{
$q = $this->createQuery('c')
->where('c.id = ? ', $id)
->addWhere('c.userid = ? ', $userid);
return $q->execute();
}
I tried it with and without the ->execute(), did doctrine clean, cleared cache, rebuilded model,
Always get the same error 'The "%s" form only accepts a "%s" object.
If I use the Doctrine_Core::getTable('BambinbazarArticles')->find() it work, but of course, i need more than that..
I am becoming crazy over this.
execute() can return multiple rows; effectively you're getting a recordset back, rather than the individual object that your form is expecting. Try fetching a single object, using, e.g.:
return $q->execute()->getFirst();
or
return $q->fetchOne();
Its probably because your query is returning a Doctrine_Collection, not the actual Doctrine_Record youre expecting. Instead of execute use fetchOne.
public function getMyAd($id, $userid)
{
$q = $this->createQuery('c')
->where('c.id = ? ', $id)
->addWhere('c.userid = ? ', $userid)
->limit(1);
return $q->fetchOne();
}