Add a new value to insert it - codeigniter

hello i have this function insertion works very well
function add_post(){
$this->form_validation->set_rules('user_id','User Id','trim|required');
//set msg if form validation false
if($this->form_validation->run() == FALSE){
$response = array('status' => FAIL, 'message' => strip_tags(validation_errors()));
$this->response($response);
}
$is_exist = $this->common_model->getsingle(USERS,array('userId'=>$this->post('user_id')));
if($is_exist){
$is_active = $this->common_model->getsingle(USER_COUPON,array('user_id'=>$is_exist->userId,'status'=>1));
$data['user_id'] = $is_exist->userId;
$data['user_coupon_id'] = $is_active->userCouponId;
$data['email'] = $is_exist->email;
$result = $this->common_model->insertData(USER_COUPON_SCAN,$data);
$response = array('status' => SUCCESS, 'message' => "success");
$this->response($response);
}
$response = array('status' => FAIL,'message' =>"No record found please try again");
$this->response($response);
}
the function recovers a single value user_id,I want to get a new value send by post (name admin_id) and isert in user_coupan_scan table

If you are sure that your code is working well, You can receive posted admin_id in following way.
function add_post(){
$this->form_validation->set_rules('user_id','User Id','trim|required');
//set msg if form validation false
if($this->form_validation->run() == FALSE){
$response = array('status' => FAIL, 'message' => strip_tags(validation_errors()));
$this->response($response);
}
$is_exist = $this->common_model->getsingle(USERS,array('userId'=>$this->post('user_id'))); // You may need to change $this->post('user_id') to $this->input->post('user_id')
if($is_exist){
$is_active = $this->common_model->getsingle(USER_COUPON,array('user_id'=>$is_exist->userId,'status'=>1));
$data['admin_id'] = $this->input->post('admin_id'); // make sure that the column name in your table is admin_id
$data['user_id'] = $is_exist->userId;
$data['user_coupon_id'] = $is_active->userCouponId;
$data['email'] = $is_exist->email;
$result = $this->common_model->insertData(USER_COUPON_SCAN,$data);
$response = array('status' => SUCCESS, 'message' => "success");
$this->response($response);
}
$response = array('status' => FAIL,'message' =>"No record found please try again");
$this->response($response);
}
In above answer, I have added one line i.e. receiving admin_id in post data.
$data['column_name_in_your_table'] = $this->input->post('name_in_post_data');
To receive data from post method you can do it like this
$some_name = $this->input-post('name');
Hope it helps.

Related

Validation can not updating value in database

I am uses validation for gst and adhar but when its error free i am updating value but value can not updating. I am giving updating code in else part. what is mistake done by me? need a solution. In if part i am checking validation and in else part if error is not coming, i am updating value from table but i can not work.
public function profile_update(Request $req,$id)
{
$mytime = Carbon::now();
$fullname = $req->input('fullname');
$email = $req->input('email');
$mobile = $req->input('mobile');
$gender = $req->input('gender');
$gstnumber = $req->input('gst_number');
$adharnumber = $req->input('aadhar_number');
$password = $req->input('password');
$cpassword = $req->input('c_password');
$updated_at = $mytime->toDateTimeString();
$created_at = $mytime->toDateTimeString();
$validator = Validator::make($req->all(), [
'email' => 'email|unique:users,email',
'aadhar_number' => 'unique:users,aadhar_number' ,
'gst_number' => 'regex:^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$^|unique:users,gst_number'
]);
if($validator->fails())
{
//dd("hello");
$messages = $validator->messages();
//return Redirect::to('/customer')->with('message', 'Register Failed');
return redirect('/profile')
->withErrors($validator)
->withInput();
}
else
{
if ($req->hasFile('update_image'))
{
$image = $req->file('update_image');
$filename = $image->getClientOriginalName();
$destinationPath = public_path('/images/users_profile/');
$image->move($destinationPath, $filename);
DB::update(
'update users set name = ?,email = ?,mobile = ?,image = ?,gender = ?,gst_number=?,aadhar_number=?,password = ?,cpassword = ? where id = ?',
[$fullname, $email, $mobile, $filename, $gender, $gstnumber, $adharnumber, $password, $cpassword, $id]
);
}
else
{
DB::update(
'update users set name = ?,email = ?,mobile = ?,gender = ?,gst_number=?,aadhar_number=?,password = ?,cpassword = ? where id = ?',
[$fullname, $email, $mobile, $gender, $gstnumber, $adharnumber, $password, $cpassword, $id]
);
}
return redirect('/profile');
}
}
you dont need the if else statement
$req->validate([
'email' => 'email|unique:users,email',
'aadhar_number' => 'unique:users,aadhar_number' ,
'gst_number' => 'regex:^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$^|unique:users,gst_number'
// continue your update code here
]);
Simply do this and it will do the needfull for you
if your conditions are not met by the values it will return to the previous view and if the conditions are met, it will continue to run the codes.
for updating the data
$data = user::find(id);
$data->name = $name;
$data->email = $email;
.
.
.
.
//update all the fields
$data->save();

Guzzle POST request: required body when execute request

I have a POST request with Guzzle like this:
// Return a collection
$cart = $this->getCart('2019-10-08 07:08:39');
//Return first entry of the collection with first()
$template = $this->getTemplate($config->key);
$isDetail = null;
foreach ($cart as $item) {
try {
$client = $this->getClient();
$headers = ['Content-Type' => 'application/json'];
$body = [
'user_id' => $item->mystore_user_id,
'title' => $template->title,
'message' => $template->message,
'avatar' => $template->avatar,
'detail_id' => $isDetail,
'schedule' => null
];
print_r($body);
$response = $client->post('push-noti/unicast', $headers, $body);
print_r(response()->json(json_decode($response->getBody(), true)));
} catch (QueryException | \Exception $ex) {
echo "Error!";
}
}
My body variable value is exist in each loop when it printed. But when I use it in $client->post, my request return error with user_id, title, message is required. I really don't know why is it?
Can you tell me what's wrong in my code?
Thank you!
Try
$response = $client->post('push-noti/unicast', ['body' => $body , 'headers' => $headers]);
If you are calling a third party API, replace push-noti/unicast with complete URL.

Laravel 4 code organization

I have some questions to Laravel 4 code organization. I am not the best "clean coder" and come from the Java world and sometimes my PHP / Laravel 4 code looks terrible. I post an example here from my controller:
public function postCreate()
{
$input = array(
'title' => Binput::json('title'),
'gender' => Binput::json('gender'),
'first' => Binput::json('first'),
'last' => Binput::json('last'),
'birthdate' => Binput::json('birthdate'),
'birthplace' => Binput::json('birthplace'),
'citizenship' => Binput::json('citizenship'),
'organizationId' => Binput::json('organizationId'),
'typeId' => Binput::json('typeId'),
'email' => Binput::json('email'),
'phone_private' => Binput::json('phone_private'),
'phone_mobile' => Binput::json('phone_mobile'),
'address_street' => Binput::json('address.street'),
'address_postcode' => Binput::json('address.postcode'),
'address_city' => Binput::json('address.city'),
'address_country' => Binput::json('address.country'),
'educations' => Binput::json('educations'),
'selectedLanguages' => Binput::json('selectedLanguages'),
'work' => Binput::json('work'),
);
$rules = array (
'gender' => 'required|max:1',
'first' => 'required|min:2',
'last' => 'required|min:2',
'birthdate' => 'required',
'organizationId' => 'required',
'typeId' => 'required',
'email' => 'required|email',
);
$v = Validator::make($input, $rules);
if ($v->fails() || empty($input['educations']))
{
$data = array("flash" => 'Firstname, Lastname, Birthdate, Email and at least 1 entry in Educations required.');
return Response::json($data, 500);
}
try {
DB::connection()->getPdo()->beginTransaction();
$member = new Member();
$member->title = $input['title'];
$member->gender = $input['gender'];
$member->first = $input['first'];
$member->last = $input['last'];
$member->birthdate = $input['birthdate'];
$member->birthplace = $input['birthplace'];
$member->citizenship = $input['citizenship'];
$work = new Work();
$work->working = $input['work']['working'];
if($input['work']['working'] == 1){
$work->branch = $input['work']['branch'];
$work->company = $input['work']['company'];
}
$work->save();
$member->work()->associate($work);
$member->save();
foreach($input['educations'] as $eduInput){
$edu = new Education();
$edu->degree = $eduInput['degree'];
if(!empty($eduInput['course'])){
$edu->course = $eduInput['course'];
}
$edu->term = $eduInput['term'];
$edu->completion = $eduInput['completion'];
if(!empty($eduInput['faculty'])){
try{
$faculty = Faculty::findOrFail($eduInput['faculty']['id']);
$edu->faculty()->associate($faculty);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}
if($eduInput['institutionId'] == 0){
// University
try{
$university = University::findOrFail($eduInput['university']['id']);
$edu->university()->associate($university);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}else{
// Freetext
$edu->institution = $eduInput['institution'];
}
$edu->save();
$member->educations()->save($edu);
}
foreach($input['selectedLanguages'] as $languageInput){
try{
$lang = Language::findOrFail($languageInput['id']);
$member->languages()->attach($lang);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}
try{
$memberType = MemberType::findOrFail($input['typeId']);
$member->memberType()->associate($memberType);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
try{
$organization = Organization::findOrFail($input['organizationId']);
$member->organizations()->attach($organization);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
$email = new Email();
$email->email = $input['email'];
$email->primary = true;
$member->emails()->save($email);
// If input for phone is empty
$phone = new Phone();
$phone->phone = $input['phone_private'];
$phone->phoneType()->associate(PhoneType::find(PhoneType::PRIVATE_PHONE));
$member->phones()->save($phone);
$phone = new Phone();
$phone->phone = $input['phone_mobile'];
$phone->phoneType()->associate(PhoneType::find(PhoneType::MOBILE_PHONE));
$member->phones()->save($phone);
$address = new Address();
$address->street = $input['address_street'];
$address->postcode = $input['address_postcode'];
$address->city = $input['address_city'];
$address->country = $input['address_country'];
$address->member()->associate($member);
$address->save();
DB::connection()->getPdo()->commit();
}catch (\PDOException $e) {
DB::connection()->getPdo()->rollBack();
return Response::json("Error while writing to database.", 500);
}
$member->load('emails');
$data = array("flash" => 'Member created successfully.');
return Response::json($data, 200);
}
This is an example from my controller.
Is it normal to get all parameters in this way. It takes much of space.
Can I move my database transaction elsewhere and not storing in the controller ?
In general where to store the code that manages logic ? In the controller ? In the
model ?
Your controller actions are just a sort of middleware in the sense that in there you should not put any of your business logic. a few pointers I can provide:
you can get all the json input with Input::json()->all() which returns an array so you can operate it.
Validation rules are another responsibility so it should be abstracted in another class that you call from the controller, it also may be well suited in your models(or entities).
To help you understand how can you use another class inside your controllers you should look for dependency injection in the laravel docs.
if you can get access to this book https://leanpub.com/laravel by Laravel's creator it will help your understanding of code organization and class responsibilities even outside laravel

HybridAuth send tweet with image

I'm using the HybridAuth library.
I'd like to be able to post message to my authenticated users twitter profile with images.
The setUserStatus method works well to automatically send a tweet.
I wrote the following method :
function setUserStatus( $status, $image )
{
//$parameters = array( 'status' => $status, 'media[]' => "#{$image}" );
$parameters = array( 'status' => $status, 'media[]' => file_get_contents($image) );
$response = $this->api->post( 'statuses/update_with_media.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
The message I get from twitter is :
Ooophs, we got an error: Update user status failed! Twitter returned an error. 403 Forbidden: The request is understood, but it has been refused.
How Can I get more precise info about error ?
Does anybody allready success in sending a picture attached to a tweet ?
Thanks !
Hugo
Thanks #Heena for making myself wake up on this question, I MADE IT ;)
function setUserStatus( $status )
{
if(is_array($status))
{
$message = $status["message"];
$image_path = $status["image_path"];
}
else
{
$message = $status;
$image_path = null;
}
$media_id = null;
# https://dev.twitter.com/rest/reference/get/help/configuration
$twitter_photo_size_limit = 3145728;
if($image_path!==null)
{
if(file_exists($image_path))
{
if(filesize($image_path) < $twitter_photo_size_limit)
{
# Backup base_url
$original_base_url = $this->api->api_base_url;
# Need to change base_url for uploading media
$this->api->api_base_url = "https://upload.twitter.com/1.1/";
# Call Twitter API media/upload.json
$parameters = array('media' => base64_encode(file_get_contents($image_path)) );
$response = $this->api->post( 'media/upload.json', $parameters );
error_log("Twitter upload response : ".print_r($response, true));
# Restore base_url
$this->api->api_base_url = $original_base_url;
# Retrieve media_id from response
if(isset($response->media_id))
{
$media_id = $response->media_id;
error_log("Twitter media_id : ".$media_id);
}
}
else
{
error_log("Twitter does not accept files larger than ".$twitter_photo_size_limit.". Check ".$image_path);
}
}
else
{
error_log("Can't send file ".$image_path." to Twitter cause does not exist ... ");
}
}
if($media_id!==null)
{
$parameters = array( 'status' => $message, 'media_ids' => $media_id );
}
else
{
$parameters = array( 'status' => $message);
}
$response = $this->api->post( 'statuses/update.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
To make it work you have to do like this :
$config = "/path_to_hybridauth_config.php";
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Twitter" );
$twitter_status = array(
"message" => "Hi there! this is just a random update to test some stuff",
"image_path" => "/path_to_your_image.jpg"
);
$res = $adapter->setUserStatus( $twitter_status );
Enjoy !
I did not understand it for hybridauth then I used this library
https://github.com/J7mbo/twitter-api-php/archive/master.zip
Then I was successful using code below: (appears elsewhere in stack)
<?php
require_once('TwitterAPIExchange.php');
$settings= array(
'oauth_access_token' => '';
'oauth_access_secret' => '';
'consumer_key' => '';
'consumer_secret' => '';
// paste your keys above properly
)
$url_media = "https://api.twitter.com/1.1/statuses/update_with_media.json";
$requestMethod = "POST";
$tweetmsg = $_POST['post_description']; //POST data from upload form
$twimg = $_FILES['pictureFile']['tmp_name']; // POST data of file upload
$postfields = array(
'status' => $tweetmsg,
'media[]' => '#' . $twimg
);
try {
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url_media, $requestMethod)
->setPostfields($postfields)
->performRequest();
echo "You just tweeted with an image";
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>

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