Codeigniter db queries is not capturing some specific queries - codeigniter

am trying to capture all queries and record a log of interactions, however some queries are not being captured, this specific query for example:
$this->db->update('showtec.motoristas', $motorista);
I capture the queries using the Hooks function like this:
Hooks.php:
$hook['post_controller'] = array(
'class' => 'Db_query_log',
'function' => 'log_db_queries',
'filename' => 'db_log.php',
'filepath' => 'hooks'
);
db_log.php:
<?php
class Db_query_log {
function __construct() {
}
function log_db_queries() {
$CI =& get_instance();
$CI->load->model('auditoria');
$data = array();
$queries = $CI->db->queries;
$data['id_usuario_gestor'] = $CI->auth->get_login('id_user');
foreach ($queries as $query){
if (preg_match($pattern = '/' . 'INSERT' . '/', $query)){
$queryArray = explode("`", $query);
if($queryArray[3] != 'ip'){
$data['query'] = $query;
$data['clause'] = 'insert';
break;
}
}elseif (preg_match($pattern = '/' . 'UPDATE' . '/', $query)){
$data['query'] = $query;
$data['clause'] = 'update';
break;
}elseif (preg_match($pattern = '/' . 'DELETE' . '/', $query)){
$data['query'] = $query;
$data['clause'] = 'delete';
break;
}
}
if(array_key_exists('query', $data)){
$CI->auditoria->salvarAuditoria($data);
}
}
}

Related

Error updating data of 1 column by id in Codeigniter 3 database

I am posting the hosting order and I want to increase the "number of sales" column in my "hostings" table, but the data of all packages in my hostings table is increasing.
Here is my relevant code, I can say that there is no method I haven't tried.
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->update('hostings', $data);
//FULL CODE
public function buy_hosting_post()
{
if ($this->input->post('package_id') && $this->session->userdata('id')) {
$hosting = $this->db->from('hostings')->where('id', $this->input->post('package_id'))->get()->row_array();
if ($hosting) {
$data = array(
'user_id' => $this->session->userdata('id'),
'domain' => $this->input->post('domain'),
'price' => $this->input->post('price'),
// 'end_date' => date('Y-m-d h:i:s',$end_date),
'package_id' => $hosting['id'],
'package_title' => $hosting['name'],
'payment_status' => 0,
);
$this->db->insert('hosting_orders', $data);
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->update('hostings', $data);
$hosting_order_successful = array(
'hosting_order_successful' => 'success',
);
$this->session->set_userdata('hosting_order_successful', $hosting_order_successful);
redirect(("hosting-siparisi-olusturuldu"));
} else {
redirect(base_url());
}
} else {
redirect(base_url());
}
}
I solved the problem in the following way, but it makes the system heavy.
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->where('id', $this->input->post('package_id')); // added here.
$this->db->update('hostings', $data);

I want to store a value to my variable using eloquent

I want to check the Referal Model for the value and when the value matches with my input I have to pay rupees 350 else I have to pay 375 .But I am redirect to pay 350 everytime even if I have entered invalid code
I have tried this logic but it didn't worked
use App\Theme_User;
use App\Theme;
use App\activity_users;
use Illuminate\Http\Request;
use App\User;
use App\Referal;
use Illuminate\Support\Facades\Auth;
public function pay(Request $request){
$api = new \Instamojo\Instamojo(
config('services.instamojo.api_key'),
config('services.instamojo.auth_token'),
config('services.instamojo.url')
);
$referral = $request->input('refer');
$valid_referral = Referal::select('referal_code')->where('referal_code', $referral)->get();
Theme_User::where('Payment_id', '=', 'Dummy')->delete();
$sale_rel = new Theme_User;
$sale_rel->User_id = Auth::user()->id;
if($request->input('purpose') === "Gratitude Theme")
$sale_rel->Theme_id = 1;
$sale_rel->Payment_id = "Dummy"; //$response['payments'][0]['payment_id'];
$sale_rel->Address = $request->input('address');
$sale_rel->Unlock_key = \Uuid::generate()->string;
$sale_rel->referal_id = $referral;
$sale_rel->Unlocked = 0;
$sale_rel->save();
if($referral == $valid_referral){
try {
$response = $api->paymentRequestCreate(array(
"purpose" => $request->input('purpose'),
"amount" => 350,
"buyer_name" => Auth::user()->name,
"send_email" => true,
"email" => Auth::user()->email,
"redirect_url" => "http://127.0.0.1:8000/pay-success"
));
header('Location: ' . $response['longurl']);
exit();
}catch (Exception $e) {
print('Error: ' . $e->getMessage());
}
}
else{
try {
$response = $api->paymentRequestCreate(array(
"purpose" => $request->input('purpose'),
"amount" => 375,
"buyer_name" => Auth::user()->name,
"send_email" => true,
"email" => Auth::user()->email,
"redirect_url" => "http://127.0.0.1:8000/pay-success"
));
header('Location: ' . $response['longurl']);
exit();
}catch (Exception $e) {
print('Error: ' . $e->getMessage());
}
}
}
I want to pay rupees 350 when I have a valid referal code else I have to pay 375
Try it.
use App\Theme_User;
use App\Theme;
use App\activity_users;
use Illuminate\Http\Request;
use App\User;
use App\Referal;
use Illuminate\Support\Facades\Auth;
public function pay(Request $request){
$api = new \Instamojo\Instamojo(
config('services.instamojo.api_key'),
config('services.instamojo.auth_token'),
config('services.instamojo.url')
);
Theme_User::where('Payment_id', '=', 'Dummy')->delete();
$sale_rel = new Theme_User;
$sale_rel->User_id = Auth::user()->id;
if($request->input('purpose') === "Gratitude Theme")
$sale_rel->Theme_id = 1;
$sale_rel->Payment_id = "Dummy"; //$response['payments'][0]['payment_id'];
$sale_rel->Address = $request->input('address');
$sale_rel->Unlock_key = \Uuid::generate()->string;
$sale_rel->referal_id = $referral;
$sale_rel->Unlocked = 0;
$sale_rel->save();
$amount = 375;
$valid_referral = Referal::select('referal_code')->where('referal_code', $request->input('refer'))->first();
if(!empty($valid_referral)){
$amount = 350;
}
try {
$response = $api->paymentRequestCreate(array(
"purpose" => $request->input('purpose'),
"amount" => $amount,
"buyer_name" => Auth::user()->name,
"send_email" => true,
"email" => Auth::user()->email,
"redirect_url" => "http://127.0.0.1:8000/pay-success"
));
header('Location: ' . $response['longurl']);
exit();
}catch (Exception $e) {
print('Error: ' . $e->getMessage());
}
}
Use
$valid_referral = Referal::select('referal_code')->where('referal_code', $referral)->first();
Instead of
$valid_referral = Referal::select('referal_code')->where('referal_code', $referral)->get();
get() gives you a collection which you need to iterate to get values but first() gives you an object. In your case you need the object. Not the collection.

getting an error Undefined property: stdClass::$id

I've issue with my CMS whenever I tried to Add new page with the following line of code
<?php echo form_open_multipart('admin/page/edit/'. $page->id); ?>
it gives me error
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$id
Filename: page/edit.php
Line Number: 5
my edit function is this which perform add & update functionality
public function edit($id = NULL) {
//Fetch a page or set new one
if ($id) {
$this->data['page'] = $this->page_m->get($id);
count($this->data['page']) || $this->data['errors'][] = 'Page Could not be found';
} else {
$this->data['page'] = $this->page_m->get_new();
}
$id == NULL || $this->data['page'] = $this->page_m->get($id);
//Pages for dropdown
$this->data['pages_no_parents'] = $this->page_m->get_no_parents();
//dump($this->data['pages_no_parents']);
//Setup form
$rules = $this->page_m->rules;
$this->form_validation->set_rules($rules);
//Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->page_m->array_from_post(array(
'title',
'slug',
'order',
'body',
'template',
'parent_id',
'filename'
));
/* * ***********WORKING FOR IMAGE UPLOAD AND SAVE PATH TO DATABASE*************** */
if (!empty($_FILES['filename'])) {
$fdata = $this->do_upload('filename'); /// you are passing the parameter here
$data['filename'] = base_url() . 'uploads/' . $fdata;
}
$this->page_m->save($data, $id);
// echo '<pre>' . $this->db->last_query() . '</pre>';
redirect('admin/page');
}
//Load the view
$this->data['subview'] = 'admin/page/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function do_upload($field_name) { // but not retriveing here do this
$field_name = 'filename';
$config = array(
'allowed_types' => '*',
'max_size' => '1024',
'max_width' => '1024',
'max_height' => '768',
'upload_path' => './uploads/'
);
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload($field_name)) {
echo $this->upload->display_errors();
die();
$this->data['error'] = array('error' => $this->upload->display_errors());
//$this->data['subview'] = 'admin/page/edit';
//$this->load->view('admin/_layout_main', $this->data);
} else {
$fInfo = $this->upload->data();
//return $fInfo['file_path'].$fInfo['file_name'];
// $this->filename = $fInfo;
return $fInfo['file_name'];
}
}
<?php echo form_open_multipart('admin/page/edit/'. ((isset($page->id)) ? $page->id : '')); ?>
As I mentioned in my comment, if you are creating a new record (I assume:) your page object will not have an id yet, so you just have to do a quick check to make sure it exists and if not output an empty string.

Varien_File_Uploader is not uploading files in custom module in magento

I am trying to save the images in my module but the images are not saving from the form.
$uploader = new Varien_File_Uploader('image'); this code is not working I dont know why. The loop breaks on this line and the control get out of the loop from here. How can I save the images.
Here is my save function in the controller
public function saveAction()
{
if ($this->getRequest()->getPost())
{
try
{
$postData = $this->getRequest()->getPost();
//echo "<pre>";print_r($postData); exit;
$articleModel = Mage::getModel('blog/article');
$imgFilename = NULL;
if($_FILES['image']['name'] != '')
{//echo "<pre>"; echo count($_FILES['image']['name']);
foreach($_FILES['image']['name'] as $_FILES['image']['name'])
{
//print_r($_FILES['image']['name']);
try
{ echo "1";
$uploader = new Varien_File_Uploader('image'); echo "hi";
//print_r($uploader);exit;
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png','flv'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$uploader->setAllowCreateFolders(true);
// Set media as the upload dir
$media_path = Mage::getBaseDir('media') . DS . 'blog' . DS;
$imgFilename = time() . $postData['image'];
// Upload the image
//$uploader->save($media_path, $_FILES['image']['name']);echo "4";
$uploader->save($media_path, $imgFilename);
}
catch (Exception $e)
{
Mage::log($e);
$this->_redirectError(502);
}
$data['image'] = $imgFilename;
}
}
else
{
if(isset($data['image']['delete']) && $data['image']['delete'] == 1)
$data['image'] = '';
else
unset($data['image']);
}
//echo "out"; exit;
if( $this->getRequest()->getParam('id') <= 0 )
$articleModel->setCreatedTime(
Mage::getSingleton('core/date')
->gmtDate());
$articleModel
->addData($postData)
->setUpdatedTime(
Mage::getSingleton('core/date')
->gmtDate())
->setId($this->getRequest()->getParam('id'))
->save();
$lastid = $articleModel->getId();
if($data['image'] != '')
{
foreach($data['image'] as $img)
{
$imageModel=Mage::getModel('blog/image');
$imageModel->setArticleId($lastid)->setImage($data['image'])->save();
}
}
Mage::getSingleton('adminhtml/session')
->addSuccess('successfully saved');
Mage::getSingleton('adminhtml/session')
->setarticleData(false);
$this->_redirect('*/*/');
//return;
if ($this->getRequest()->getParam('back'))
{
$this->_redirect('*/*/edit',array('id' => $articleModel->getId()));
return;
}
}
catch (Exception $e)
{
Mage::getSingleton('adminhtml/session')
->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')
->setarticleData($this->getRequest()
->getPost());
$this->_redirect('*/*/edit',
array('id' => $this->getRequest()
->getParam('id')));
return;
}
}
$this->_redirect('*/*/');
}
and here is my form for the image
<?php
class Vertax_Blog_Block_Adminhtml_Article_Edit_Tab_Image extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('image_form',
array('legend'=>'image'));
//$fieldset->addType('image', Mage::getConfig()->getBlockClassName('blog/adminhtml_article_helper_image'));
$fieldset->addType('image', 'Vertax_Blog_Block_Adminhtml_Article_Helper_Image');
$fieldset->addField('image', 'image', array(
'label' => 'Image',
'required' => false,
'name' => 'image[]',
'multiple' => 'multiple',
'mulitple' => true,
));
if (Mage::getSingleton('adminhtml/session')->getBlogPostData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getBlogPostData());
Mage::getSingleton('adminhtml/session')->setBlogPostData(null);
} elseif (Mage::registry('article_data')) {
$form->setValues(Mage::registry('article_data')->getData());
}
return parent::_prepareForm();
}
}
?>
$uploader = new Mage_Core_Model_File_Uploader(
array(
'name' => $_FILES['galleryImage']['name'][$i],
'type' => $_FILES['galleryImage']['type'][$i],
'tmp_name' => $_FILES['galleryImage']['tmp_name'][$i],
'error' => $_FILES['galleryImage']['error'][$i],
'size' => $_FILES['galleryImage']['size'][$i]
));
Waseem,please try code for upload image..
$uploader = new Mage_Core_Model_File_Uploader('image');
$uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
$uploader->setFilesDispersion(true);
$media_path = Mage::getBaseDir('media') . DS . 'blog' . DS;
$imgFilename = time() . $postData['image'];
// Upload the image
//$uploader->save($media_path, $_FILES['image']['name']);echo "4";
$uploader->save($media_path, $imgFilename);
there was a problem in your code while adding fieldset
$fieldset->addField('image', 'image', array(
'label' => 'Image',
'required' => false,
'name' => 'image[]',
'multiple' => 'multiple',
'mulitple' => true,
));
here you had set the name to image[] which in turn will return the array as $_FILES['image][name][], $_FILES['image][tmp_name][].
If you want to upload single file then set 'name' = 'image' or see this question
Try to use
$uploader = new Varien_File_Uploader($_FILES['image']);
instead of what you use currently.

CodeIgniter Captcha is not working

I am at my wits end and don't know why my code is not working . Everything seems good to me .. I have implemented a captcha in my user review function and added a verification method using callback_ .
The captcha is showing in the view and i have dumped the session data and the input field data and they are both working.
The form validation is also working in case of captcha input field but seems like the callback_check_captcha parameter is not working but the function seems fine to me .
Here is my controller
function user_review($id = null , $start = 0){
$check_id = $this->mdl_phone->get_phone_feature($id);
if ($check_id == null ) {
$data['phone_model'] = $this->get_phone_models();
$data['feature'] = null;
$data['title'] = 'Nothing Found';
$data['main_content']= 'phone/error';
echo Modules::run('templates/main',$data);
} else{
$data['phone_model'] = $this->get_phone_models();
$data['success'] = null;
$data['errors'] = null;
if($this->input->server("REQUEST_METHOD") === 'POST' ){
$this->load->library('form_validation');
$this->form_validation->set_rules('text','Review','required|xss_clean');
$this->form_validation->set_rules('captcha', 'Captcha','trim|required|callback_check_captcha');
if($this->form_validation->run() == FALSE){
$data['errors'] = validation_errors();
}else{
$user = $this->ion_auth->user()->row();
$user_id = $user->id;
$data = array(
'phone_id' => $id,
'user_id' => $user_id,
'text' => strip_tags($this->input->post('text')),
);
$this->db->insert('user_review' ,$data);
$data['phone_model'] = $this->get_phone_models();
$data['success'] = 'Your Review has been successfully posted ';
$data['errors']= null;
}
}
// Initilize all Data at once by $id
$data['feature'] = $this->mdl_phone->get_phone_feature($id);
//$data['rating'] = $this->mdl_phone->get_user_rating($id);
$data['user_review'] = $this->mdl_phone->get_user_review($id , 5 , $start);
$this->load->library('pagination');
$config['base_url'] = base_url().'phone/user_review/'.$id;
$config['total_rows'] = $this->mdl_phone->get_user_review_count($id);
$config['per_page'] = 5;
$config['uri_segment'] = 4;
$config['anchor_class'] = 'class="page" ';
$this->pagination->initialize($config);
$this->load->helper('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => base_url().'captcha/',
'img_width' => 150,
'img_height' => 30,
);
$cap = create_captcha($vals);
$this->session->set_userdata('captcha',$cap['word']);
$data['captcha'] = $cap['image'];
$data['title'] = $this->mdl_phone->get_phone_title($id)." User Review , Rating and Popularity";
$data['main_content'] = 'phone/user_review';
echo Modules::run('templates/main',$data);
}
}
function check_captcha($cap)
{
if($this->session->userdata('captcha') == $cap )
{
return true;
}
else{
$this->form_validation->set_message('check_captcha', 'Security number does not match.');
return false;
}
}
The bellow CAPTHA working properly refer this code
$this->load->helper('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => base_url() . '/captcha/'
);
$cap = create_captcha($vals);
$data = array(
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$this->session->set_userdata($data);
$data['cap_img'] = $cap['image'];
I think your image url problem or you are not giving a file permission to the captha folder .

Resources