File upload with text fields in codeigniter using upload class - html

I have a form in which there are both types of fieldsmeans inputs text , radio , select , textarea and file upload fields.
I am using the same form for insert and edit.
My problem is that i have to upload file and insert the data in the table.
Controller functions
function myUploadwithInsert(){
if($category = $this->input->post())
{
$this->load->library('form_validation');
if(!$this->imageUpload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('my_view', $error);
}else{
$this->form_validation->set_rules('name', 'Category Title', 'trim|required');
if ($this->form_validation->run() == TRUE)
{
if ($id = $this->categories_model->create($category))
{
redirect('admin/categories');
}
}else{
$this->load->view('my_view');
}
}
}else{
$this->load->view('my_view');
}
}
public function uploadImage()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
return false;
}
else
{
$data = $this->upload->data();
return $data;
}
}
Now the problem is that if image is uploaded and there come a form input error form will be displayed again user rectifies the form fields and fills the image field again. Then the image will be uploaded again.
The same thing goes when i define the input condition first and then upload the same problem rises. How can i ivercome this problem? Is there anyother way to do this task.

After a little research i have found a solution here
Using Codeigniter Form Validation Library
http://codeigniter.com/user_guide/libraries/form_validation.html
And
http://keighl.com/post/codeigniter-file-upload-validation
A great article. Solver my problem

Related

not responding while login

I am new to CodeIgniter, and am trying to write code to log in after registering using a username and password in registration form using a PHPMyAdmin database. I am not getting anything when I try to log in, and it doesn't display an error or any message.
public function login() {
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password' , 'Password');
if($this->form_validation->run() == TRUE){
//check user in database
$this->db->select('username' , 'password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user = $query->row();
if($user->email){
$this->session->set_flashdata("Successful login");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
} else {
$this->session->set_flashdata("Error No such record found");
}
}
// load view and showing login form
$this->load->view('login');
}
First, you should read the documentation, looks like you skip that part, but it's very important!
Let's code a little bit and fix the bugs!
User data
Well, users will enter their data and we will check, if evertyhing is correct, we can redirect user to the protected page. You call for variables (see Query:) but you I'm not seeing on your code. You should put like that, before your query job
$username = $this->input->post("username");
$password = $this->input->post("password");
Now, you will be able to use the where to get the user data. =)
Query:
If read about OOP with PHP, you know that when you pass parameters to a method, each parameter have their own "action". In case of the select method, you should keep the data you want to select, on the same quote, because you the way you do, it's like you passing multiple parameters to the method.
$this->db->select('username, password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
First, to decide if the record exist or not, I prefer this way:
if($query->num_rows() > 0) {
$user_data = $query->row();
// We should verify if the user entered the password that correspond to the account.
// If not, we tell them that the password is incorrect.
if($password != $user_data->password) {
$this->session->set_flashdata("error", "Wrong password!");
return redirect(site_url());
}
// You can use the CI built in methods to work with sessions
$this->session->set_userdata(array(
'username' => $user_data->username,
));
$this->session->set_flashdata("success", "You are logged in!");
return redirect(site_url());
} else {
$this->session->set_flashdata("Error: No such record found");
redirect(site_url());
}
Flash data
Yeah, we use flashdata to show a message for the user. But, you should pass an item and the value of this item. Like that:
$this->session->set_flashdata('success', 'Successfully logged in!");
And, to retrieve the data on your views, you can do like...
<?php
$success = $this->session->flashdata("success");
$error = $this->session->flashdata("error");
if(!empty($success)) {
echo $success;
}
if(!empty($success)) {
echo $error;
}
?>
Recommendations
Sessions: https://codeigniter.com/userguide3/libraries/sessions.html
Database: https://www.codeigniter.com/userguide3/database/query_builder.html
Also, I recommed you, to take a minute on YouTube, to understand CodeIgniter.
If I forgot something, let me know! =)
Great Suggestion by webmasterdro's Answer.
I would like to extend it a little bit.
Looking at your code it looks like you have added the query to the controller.
And as a suggestion, if you are using an MVC framework then try to follow some basic MVC flow. because if you are not following that then it will be useless to use a framework.
User Controller to handle the post data and validations.
Use model to do the database query.
Use __construct for loading the common model or libraries.
Do not save plane password use md5 or other encryption technique.
Store User detail to the session which you can use further in after login.
Codeigniter has a great user guide. Try to follow that.
So, your code Should be your like this below.
Controller:
public function __construct() {
parent::__construct();
// Load model
$this->load->model('login_database');
}
public function your_controller_function_name() {
// Check validation for user input in SignUp form
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form_view');
} else {
$username = $this->input->post("username");
$password = $this->input->post("password");
$result = $this->login_database->registration_insert($username, $password);
//You can do this also if($result != FALSE)
if (!empty($result)) {
// You can set other data to the session also form here
$session_data = array(
'username' => $result['user_name']
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
// You can set flash data here
$this->load->view('your_view');
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('your_login_form_view', $data);
}
}
}
Model:
// Read data using username and password
public function login($username, $password) {
$this->db->select('username');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user_data = $query->row_array();
if ($query->num_rows() == 1) {
return user_data;
} else {
return false;
}
}
I have not added detail related to flash data because the previous answer has explained it properly.

how to let magento send different mails with different information for every payment method

My New Order email already uses {{var payment_html}} and I already have a custom note for customers who select MoneyGram, Western Union and Money Transfer payment methods. I need to send different information for every single payment method in the email being sent.
you need to override sendNewOrderEmail() in /app/code/core/Mage/Sales/Model/order.php
in this function just check the payment and dynamically pass the value to array.
public function sendNewOrderEmail()
{
$storeId = $this->getStore()->getId();
if (!Mage::helper('sales')->canSendNewOrderEmail($storeId)) {
return $this;
}
// Get the destination email addresses to send copies to
$copyTo = $this->_getEmails(self::XML_PATH_EMAIL_COPY_TO);
$copyMethod = Mage::getStoreConfig(self::XML_PATH_EMAIL_COPY_METHOD, $storeId);
// Start store emulation process
$appEmulation = Mage::getSingleton('core/app_emulation');
$initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId);
try {
// Retrieve specified view block from appropriate design package (depends on emulated store)
$paymentBlock = Mage::helper('payment')->getInfoBlock($this->getPayment())
->setIsSecureMode(true);
$paymentBlock->getMethod()->setStore($storeId);
$paymentBlockHtml = $paymentBlock->toHtml();
} catch (Exception $exception) {
// Stop store emulation process
$appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
throw $exception;
}
// Stop store emulation process
$appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
// Retrieve corresponding email template id and customer name
if ($this->getCustomerIsGuest()) {
$templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_GUEST_TEMPLATE, $storeId);
$customerName = $this->getBillingAddress()->getName();
} else {
$templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE, $storeId);
$customerName = $this->getCustomerName();
}
$mailer = Mage::getModel('core/email_template_mailer');
$emailInfo = Mage::getModel('core/email_info');
$emailInfo->addTo($this->getCustomerEmail(), $customerName);
if ($copyTo && $copyMethod == 'bcc') {
// Add bcc to customer email
foreach ($copyTo as $email) {
$emailInfo->addBcc($email);
}
}
$mailer->addEmailInfo($emailInfo);
// Email copies are sent as separated emails if their copy method is 'copy'
if ($copyTo && $copyMethod == 'copy') {
foreach ($copyTo as $email) {
$emailInfo = Mage::getModel('core/email_info');
$emailInfo->addTo($email);
$mailer->addEmailInfo($emailInfo);
}
}
// $orde$this->getOrderId();
$order_payment_title = $this->getOrder()->getPayment()->getMethodInstance()->getTitle();
if($order_payment_title=='moneygram'){
$paymentBlockHtml = 'moneygram html'; //custom html
}elseif($order_payment_title=='westernunion'){
$paymentBlockHtml = 'westernunion html'; //custom html
}elseif($order_payment_title=='monyetransfer '){
$paymentBlockHtml = 'monyetransfer html'; //custom html
}
// Set all required params and send emails
$mailer->setSender(Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $storeId));
$mailer->setStoreId($storeId);
$mailer->setTemplateId($templateId);
$mailer->setTemplateParams(array(
'order' => $this,
'billing' => $this->getBillingAddress(),
'payment_html' => $paymentBlockHtml
)
);
$mailer->send();
$this->setEmailSent(true);
$this->_getResource()->saveAttribute($this, 'email_sent');
return $this;
}

Updating a tinyint filed in database using codeigniter

I'm trying update a tinyint field called inactive from 0 to 1 whenever a button is clicked. I'm sure that I'm getting the correct id so there's no problem there but I can't update the field.
Here is my code for the view.
<a id="deactivate" role="button" href=<?php echo site_url('user/deactivate'); ?>>Deactivate</a>
<script>
$(document).ready(function() {
$('a#deactivate').bind('click',function(event){
if (confirm("Are you sure you want to deactivate " + id_deactivate + "?")) {
url_deactivate = ('<?php echo site_url('user/deactivate'); ?>');
$('a#deactivate').attr('href', function() {
var newURL0 = url_deactivate + "/" + id_deactivate;
console.log(newURL0);
return newURL0;
})
} else{
event.preventDefault()
}
});
});
</script>
for the model:
public function deactivateUser($id, $data){
if($this->db->update('user', "`inactive` = '".$data."'", "`user_id` = '".$id."'")){
return true;
}
return false;
}
And for the controller:
public function deactivate($id){
$this->session->set_userdata('page', 'user');
$this->session->set_userdata('action', 'view');
$data['inactive'] = 1;
$this->user_model->deactivateUser($id, $data);
redirect('user');
}
I'm pretty sure that the problem is with the controller but I don't know how to fix it. Can anyone help me? Thank you in advance.
in model try this
$this->db->where('user_id', $id);
$update = $this->db->update('user', $data);
if($update) return TRUE;
return FALSE:
See more info here
Instead of setting the href value after confirming the JS dialog (really weird way of going about it), just set the href already in the HTML.
Then you launch the JS confirm with
return (confirm("Are you sure you want to deactivate " + id_deactivate + "?")) ? true : false;
If you return true (when the user accepts the confirmation) you let the default action run its course, which is following the link in the href. If the user doesn't accept the confirmation you cancel the default action with a return false, and nothing happens.

Getting error while updating User data in cakephp2.4.0

I am getting error on saving the edited data. Actually User clicked on the edit button User is redirected to edit data page at the end (after) editing the data when user wants to save the edited data cakephp gives error sql integrity violation code 1062. The code for edit is default code generated by the cake bake. the code is
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
i also tried savefield instead of save but that is adding new user with all null fields.
You should set the id property on the user before you save it:
$this->User->id = $id;
Or make sure that in your $this->request->data;, the id of the object your are editing is present, $this->request->data['User']['id']; in this particular case, the absence of the user id on the request data is causing the problem.

Upload and Insert File Data in CodeIgniter

I'm creating a file upload system in CodeIgniter, and I have a form that asks for a file name before it uploads to the database. It uses my controller to upload the file to the server. Currently the controller is working, but I need to insert the file name into the table.
upload.php:
function do_upload()
{
$config['upload_path'] = './gfiles/';
$config['allowed_types'] = 'gif|jpg|jpeg|bmp|png|psd|pdf|eps|ai|zip|indd|qxt';
$config['encrypt_name'] = 'TRUE';
//$config['max_size'] = '100';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->db->insert('files', $_POST);
}
}
Does anyone have any pointers on how to get the file name into the database properly? The code above also encrypts the filename. Thank you.
$data = array('upload_data' => $this->upload->data()); should contain what you are looking for.
do print_r($data) and you should see the original and encrypted filename.