codeigniter update particular database row - codeigniter

I'm trying to setup my codeigniter install to allow me to update my database. I have managed to do this using :
function updateValues(){
$this->load->model("get_db");
$newrow = array(
array(
"id" => "3",
"name" => "bruce"
),
array(
"id" => "4",
"name" => "billybob"
)
);
$this->get_db->update2($newrow);
echo "update successful" ;
}
This works and updates rows 3 and 4. I now need to update a single row based on my active user ID. I've tried several lines of code found in many different places via google. Code such as:
echo $this->db->insert_id()
All this does is return a '0'.
So my question is how to I echo or return the current active users ID stored in the database.
I'm pretty sure I've missed something basic as I'm new to codeigniter. Any help would be greatly appreciated.
Thanks
Tim

Simplest way to do this is store the userId in the session when they log in, then you can just retrieve the session variable any time you need it.
Login routine
$this->db->where('userName',$userName);
$this->db->where('password',$password);
$data = $this->db->get('users');
if($data->num_rows() ==1)
{
$userData = $data->result();
$this->session->set_userdata('userId',$userData->userId);
}
Then any time you need it you just recall that userId
$userId = $this->session->userdata('userId');
$newrow = array(
'id'=>$userId,
'name'='Cornelius'
);

Related

How to get Last ID of created data from related model?

I can't fetch last id of created data from related model.
I tried to use $alacarte->id but it doesnt get the right ID of the model.
$order = array(
'os_id' => $orderSlip->id,
'group_id' => $menu['group_id'],
'size' => $menu['size'],
);
$alacarte = $this->menu->find($menu['id']);
$alacarte->orders()->create($order)->save();
return $alacarte->id;
I expect the output of the last created order to be the ID of Model\Order, but the actual output is the ID of the Model\Menu.
[Solved]
I just removed save() after creation.
$menu = $alacarte->orders()->create($order)->save()
changed to
$menu = $alacarte->orders()->create($order)
return $menu->id

Laravel: Unable to set `setTable` to eloquent model from controller

I am working in laravel 5.4 (stock management system) and have dynamic table means table generate on create new store. Each store have its own stock table with his id like store_8_stock. I create StoreStock model and when set table from controller its not working correctly:
$storeId = $item['store_id'];
unset($item['barcode']);
TransferList::create($item);
$insertStock = new StoreStock;
$insertStock->setTable('store_'.$storeId.'_stock');
$stock = $insertStock->where('item_id',$item['item_id'])->first();
if($stock != null){
$stock->qty = $stock->qty + $item['qty'];
$stock->save();
}else{
unset($item['item_name']);
unset($item['store_id']);
$insertStock->create($item);
}
for $stock = $insertStock->where('item_id',$item['item_id'])->first(); its working fine but when its coming on $insertStock->create($item); its showing error store_stocks table or view not found
$item Contains
array:11 [▼
"barcode" => "8901023007446"
"item_id" => 2
"item_name" => "My new item"
"mrp" => 12.0
"sale_price" => 60.0
"purchase_price" => 50.0
"qty" => "2"
"free_item_name" => ""
"product_vat" => 0.0
"vat_status" => 0
"store_id" => "8"
]
can any one please tell me what is wrong in my code?
This is because when you use create under the hood the newInstance() method is fired and the new instance of object has original property as defined in your model.
Probably you should use for such case something like this:
$insertStock->fill($item)->save();
to make it work.
This error and errors like it come down to the following reason:
some methods like all() create a new model instance in the background.
So when a new instance is created your setTable is gone.
The non static use of methods prefend this:
//wont work
Model::all()
// will work
$model->get()

security on insert batch? codeigniter

can anyone know how to preventing user input, on codeigniter if i use insert_batch? sorry bad english
code like this
$data[] = array(
'id_invoice' => $this->input->post('id_invoice'),
'id_product' => $key['id_product'],
'id_fabrics' => $key['id_fabric'],
'id_option' => $id_option,
'name' => $key['name'],
'number' => $key['number'],
'id_size' => $key['size'],
'comment' => $key['comment']);
and use insert batch like this
$this->orders->insert_order_mix($data);
So Simple You can remove abuse tags and data from user input
//Change This
$this->orders->insert_order_mix($data);
// to
$data = $this->security->xss_clean($data); // You have to clean Data with XSS Filtering
$this->orders->insert_order_mix($data);
This method Clean your all abuse data with [removed] keyword
if user can input any script then XSS filtering remove as per below
$name = '<script>Your Name</script>';
echo $name; // Output : <script>Your Name</script>
// But you use XSS then output is change as per below
$name = '<script>Your Name</script>';
$name = $this->security->xss_clean($name);
echo $name; // Output : [removed]Your Name[removed]
Or You can use very simple with edit your config file
// Change global_xss_filtering value FALSE to TRUE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
*/
$config['global_xss_filtering'] = TRUE;
I think you are confused with the concept of Batch Insert. Please READ THIS to get a good understanding of Batch Insert. Now for your issue, it's very good to be concerned about security these days as said
Always filter input and escape output, Never trust data.
You can Use Codeigniter Security Class to secure your data.
E.g
$data=$this->security->xss_clean($this->input->post());
OR
$postData=$this->input->post();
$data=$this->security->xss_clean($postData);
Furthermore you can avoid Cross Site Request Forgery by using CSRF token in your Forms
Thanks for your answer, i am not sure about your answer because i am using ajax to get data, and data is on array format, and this is my code to process on controller
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
} else {
$input = $this->input->post('ar_dat');
$option = $this->input->post('list_option');
if ($option == null){
$id_option = '';
} else {
$id_option = implode(',',$option);
}
foreach ($input as $key) {
$data[] = array(
'id_invoice' => $this->input->post('id_invoice'),
'id_product' => $this->input->post('id_product'),
'id_fabrics' => $this->input->post('id_fabric'),
'id_option' => $id_option,
'name' => $key['name'],
'number' => $key['number'],
'id_size' => $key['size'],
'comment' => $key['comment']);
}
$this->orders->insert_order_uniform($data);
}

Magento: Custom attributes option's new value field

I want to add a custom field in Attribute option in Manage Attribute Options menu in admin. Like value column beside the position column in admin. I have attached an image.
What I have done ... (Magento 1.8)
created a new field in eav_attribute_option table named value after sort_order filed.
changed magento\app\design\adminhtml\default\default\template\eav\attribute\options.phtml this file to show the Value column beside the Position column.
changed getOptionValues() method in this file magento\app\code\core\Mage\Eav\Block\Adminhtml\Attribute\Edit\Options\Abstract.php to get data for my custom value column from database and show in admin side. It shows the default value of db in admin form.
But when I want to save from admin panel the data doesn’t save in db.
I've been trying to find the model or controller that actually handles writing into the database to make sure my new field saves too.
Any help would be appreciated.
(I'd post an image to make you understand, but I can't since I need 10 points to be able to do it.)
Got it!
Update: Mage/Eav/Model/Resource/Entity/Attribute.php
in function: _saveOption(Mage_Core_Model_Abstract $object)
change:
$sortOrder = !empty($option[’order’][$optionId]) ? $option[’order’][$optionId] : 0;
if (!$intOptionId) {
$data = array(
‘attribute_id’ => $object->getId(),
‘sort_order’ => $sortOrder,
);
$adapter->insert($optionTable, $data);
$intOptionId = $adapter->lastInsertId($optionTable);
} else {
$data = array(’sort_order’ => $sortOrder);
$where = array(’option_id =?’ => $intOptionId);
$adapter->update($optionTable, $data, $where);
}
for this:
$sortOrder = !empty($option[’order’][$optionId]) ? $option[’order’][$optionId] : 0;
$yourAttribute = (isset($option[’your_attr_field’]) && !empty($option[’your_attr_field’][$optionId])) ? $option[’your_attr_field’][$optionId] : ‘’;
if (!$intOptionId) {
$data = array(
‘attribute_id’ => $object->getId(),
‘sort_order’ => $sortOrder,
‘your_attr_field’ => $yourAttribute
);
$adapter->insert($optionTable, $data);
$intOptionId = $adapter->lastInsertId($optionTable);
} else {
$data = array(’sort_order’ => $sortOrder, ‘your_attr_field’ => $yourAttribute);
$where = array(’option_id =?’ => $intOptionId);
$adapter->update($optionTable, $data, $where);
}
I could use some help in making all this changes 'the Magento way'

How to insert a user in the database only if there is no email address using the zend framework?

I have my controller, my function to insert into the database, and the form.
I just want to insert the user in the database if he enter the email is not already registered in the database.
My controller:
$nome = $this->_request->getParam('nome');
$senha = $this->_request->getParam('senha');
$confirmar = $this->_request->getParam('confirmar');
$email = $this->_request->getParam('email');
$usuarios = new Application_Model_DbTable_Usuarios();
$usuarios->addUsuario($nome, $senha, $email);
My DbTable_Usuario class that contains my function that inserts the user in the database
public function addUsuario($nome, $senha, $email) {
$data = array(
'id' => 'NULL',
'nome' => $nome,
'senha' => $senha,
'email' => $email,
'nivel' => '0'
);
$this->insert($data);
}
And my zend_form
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
->setRequired(true)
->addValidator('EmailAddress')
->addValidator('NotEmpty');
I have some way to add something to the form it checks if the mail entered already exists in the database? If it exists, it displays the message, and if not, insert it in the bank.
Add a Zend_Validate_Db_NoRecordExists validator to the email field.
To give a closer insight on a specific problem using NoRecordExists. The Validator is added just at the way that other validators are
$email->addValidator('Db_NoRecordExists', false, array('table'=>'usario', 'field'=>'email'));
Depending on your form setup, you will use the exact same field for EDITING a user, too. When editing a user the NoRecordExists is a little tricky. As for once, you shouldn't be allowed to change into an existing email, but you should be able to update your other data and keep your email (which though is existing in your db in the current row).
You therefore need to remove the current row from that rule. There are several approaches, which you can see from my own question, but i think the following works best from controller level:
$form = new UserForm();
$form->getElement('email')->getValidator('Db_NoRecordExists')->setExclude(array(
'field' => 'id',
'value' => $idToEdit
))

Resources