Additing two array variable in codeigniter - php

I am building a system where i need to update the value in the database field but before doing that i need to take the current value in the database then adding it to the current value the following is a code from the controller.
public function transfer_amount(){
$email = $this->input->post('view');
$this->load->model('user_model');
$data['user_balance'] = $this->user_model->fetch_balance($email);
$data['balance'] = $this->input->post('amount');
$data['total'] = $this->math->add($data['balance'],$data['user_balance']);
$data = array(
'balance' => $data['total'],
);
if($this->user_model->transfer_amount($data,$email)== true){
$this->load->view('layer_service/success',$data);
}
else
{
$this->load->view('layer_service/unsuccessfull',$data);
}
}
}
then the code in the module that fetch the current balance from the database is as following.
function fetch_balance($email){
$this->db->select('balance');
$this->db->from('tbl_users');
$this->db->where('email', $email);
$query = $this->db->get();
$result = $query->result();
return $result;
}

not sure but look at this part - don't call it $data because i think thats messing you up later
for example call it $balance
$balance = array(
'balance' => $data['total'],
);
// pass the $balance to your model method
if($this->user_model->transfer_amount($balance,$email) == true){
// keeping $data here to pass to the view
$this->load->view('layer_service/success',$data);
}
getting the balance should be wrapped in an if in case it fails
if( ! $data['user_balance'] = $this->user_model->fetch_balance($email) )
{
$this->_showNoUserFor($email) ;
}
another suggestion:
$email = $this->input->post('view');
validate the email first before sending it to your database table. codeigniter form validation library works really well.
======
EDIT ok this part
$data['total'] = $this->math->add($data['balance'],$data['user_balance']);
means that you have a model called math with a method called add()
so if you don't have that you would just use php math which is very simple
$data['total'] = $data['balance'] + $data['user_balance'] ;
of course this assumes everything has been validated first so you are actually adding together two numbers.

Related

How to check duplicate title and not save to database in laravel

i have a problem that when i get data from other api and want if same title wont save to api. Each time getting data from the api is 20 and want to save it to the database without duplicate. Please help me. Thank you very much!!!
public function getTitle($title){
$title = $this->posts->where('title', $title)->get();
return $title;
}
public function getApi(Request $request){
$url = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=87384f1c2fe94e11a76b2f6ff11b337f";
$data = Http::get($url);
$item = json_decode($data->body());
$i = collect($item->articles);
$limit = $i->take(20); // take limited 5 items
$decode = json_decode($limit);
foreach($decode as $post){
$ite = (array)$post;
$hi = $this->getTitle($ite['title']);
dd($ite['title'], $hi);
if($ite['title']==$hi){
dd('not save');
}
else{
dd('save');
}
//dd($hi, $ite['title']);
// create post
$dataPost = [
'title'=>$ite['title'],
'description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']
];
//dd($dataPost);
//$this->posts->create($dataPost);
}
return redirect()->route('posts.index');
}
You can use first or create for saving data in database if title name is new. using firstOrNew you dont have to use any other conditions
for example:-
$this->posts->firstOrCreate(
['title' => $ite['title']],
['description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']]);
firstOrNew:-
It tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new Model after applying any attributes passed in the second parameter
From docs
If any records exist that match your query's constraints, you may use
the exists and doesntExist methods
if($this->posts->where('title', $title)->doesntExist())
{
// save
} else {
// not save
}

Updating a row in Laravel 5.7 doesn't work, how do I fix it?

I'm trying to update a row in mysql table. However, when I click the register button, it doesn't do anything. I'm using Laravel.
Here's my update function:
public function update(Request $request)
{
$idpawn = $request['idprestamo'];
$paynumber = $request['numeropago'];
$payqty = $request['payqty'];
$statuspawns = statuspawns::find($idpawn,$paynumber);
$updateqty = $statuspawns->totalpayment - $payqty;
if($updateqty == "0"){
$status = "Pay";
}
else{
$status = "Partial Payment";
}
$statuspawns->total = $updateqty;
$statuspawns->status = $status;
$statuspawns->save();
return redirect()->back();
}
Thanks for your help.
I think the problem might be that you need square brackets instead of parenthesis since it's an array. $request['idprestamo']
$request['numeropago']
$request['payqty']
I'd like to also add that you can do it this way also with a magic method...
$request->numeropago
You have to access the Request this way $request->input_name not this way $request('input_name') because it is a Laravel Data Collection
In the end of the day, your function will look like this:
public function update(Request $request)
{
$idpawn = $request->idprestamo;
$paynumber = $request->numeropago;
$payqty = $request->payqty;
$statuspawns = statuspawns::find($idpawn,$paynumber);
$updateqty = $statuspawns->totalpayment - $payqty;
if($updateqty == "0"){
$status = "Pay";
}
else{
$status = "Partial Payment";
}
$statuspawns->total = $updateqty;
$statuspawns->status = $status;
$statuspawns->save();
return redirect()->back();
}
UPDATE
In Laravel 5.7 you have to use the update() method instead of the save() method to update a row.
You are not retrieving the record correctly. you have to pass only id to find(). As you have passed two parameters.
change this statement to..
$statuspawns = statuspawns::find($idpawn,$paynumber);
To
$statuspawns = statuspawns::find($idpawn);
Now you can update the columns which you want to update.

NULL Value inserted in Database (Codeigniter)

I Am trying to insert data in DB,But somehow NULL is inserted in DB
Here Is My Controller
foreach($this->input->post('resume_id') as $key =>$value ){
$ResumeInsert[$key]['resume_keyid'] = $Resume['resume_id'][$key];
$ResumeInsert[$key]['employer_name'] = $Resume['employer_name'][$key];
$ResumeInsert[$key]['start_Date'] = $Resume['start_Date'][$key];
$ResumeInsert[$key]['end_date'] = $Resume['end_date'][$key];
$ResumeInsert[$key]['type_id'] = $Resume['type_id'][$key];
$ResumeInsert[$key]['position'] = $Resume['position'][$key];
$ResumeInsert[$key]['responsibility'] = $Resume['responsibility'][$key];
$ResumeInsert[$key]['Skills'] = $Resume['Skills'][$key];
if(isset($Resume['id'][$key]) ){
$Key_Resume__ExistIDs[]=$Resume['id'][$key];
$ResumeUpdate[$key]=$ResumeInsert[$key];
$ResumeUpdate[$key]['resume_id']=$Resume['id'][$key];
unset($ResumeInsert[$key]);
}
else{
$ResumeInsert[$key]['resume_id'] = $GetLastID;
print_r ($ResumeInsert[$key]);exit;
$GetLastID++;
}
}
$idsToDelete='';
if(empty($ResumeInsert) && empty($ResumeUpdate)){
$idsToDelete=array_diff($Key_Resume_IDs,$Key_Resume__ExistIDs);
}
$status=$this->Resume_model->ProcessData($idsToDelete,$ResumeUpdate,$user_id,$ResumeInsert,$imgInsert,$imgUpdate);
redirect('Resume','refresh');
Here Is My Code Of Model
function ProcessData($idsToDelete,$tbl_resumeUpdate,$user_id,$tbl_resumeInsert,$imgInsert,$imgUpdate){
$this->db->trans_start();
if(!empty($idsToDelete)){
$this->delete_tbl_resume($idsToDelete);
}
if(!empty($tbl_resumeUpdate)){
//echo "up";exit;
$this->update_tbl_resume($tbl_resumeUpdate);
}
if(!empty($tbl_resumeInsert)){
//echo "int";exit;
$this->insert_tbl_resume($user_id,$tbl_resumeInsert);
}
if(!empty($imgInsert)){
$this->insert_tbl_file_paths($imgInsert);
}
if(!empty($imgUpdate)){
$this->update_tbl_file_paths($imgUpdate);
}
return $this->db->trans_complete();
}
This is Insert Query
function insert_tbl_resume($id,$arrtbl_resume){
$this->db->insert_batch('tbl_resume', $arrtbl_resume);
}
In Above Code,Null Value inserted In DB.
when i Print above query,it displays blank
Any Help Please?
You should use form_validation library. I'm giving you an example, you can edit and use it.
In autoload.php, edit $autoload['libraries'] = array(); line to:
$autoload['libraries'] = array('form_validation');
Then, use form_validation in your controller file. For example:
$this->form_validation->set_rules('resume_keyid', 'Resume ID', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->index() // if there is an error, user will redirect to this function
}
else
{
$this->Resume_model->ProcessData();
}
Also please use $this->input->post('resume_keyid', TRUE); structure in your model. "TRUE" means "open XSS filter". Because in CI 3, it comes off as default. If you don't want it, just remove. If you use CI 2, you don't need to add "TRUE".
A few suggestions:
1 - Don't use camelization when you name functions. For example; use process_data() instead of processData()
2 - Check CI Form Validation Document for all details (E.g. all references)
3 - I think you can use $this->db->insert();, just create an array and POST it. If you make it, you'll understand what's wrong.

Dealing with url request in CodeIgniter

I just started learning codeigniter and i must say its pretty easy but I have a problem dealing with wrong urls, for example:
if I have an anchor tag like this
http://example.com/info/2
in the controller if I have
public function info( $x ) {
$data['body'] = "Personal_info";
$data['details'] = $this->person_model->get_detail( $x );
$this->load->view('view', $data);
}
the controller grabs the links
segment (3)
and then grab the details of the id from the database.
now for instance if a user manually edit the link on the browser and change the
segment(3)
to lets say 7 and there is no id in the database as 4.
how do I handle such a problem? I am a beginner so please pardon me
You could use empty method to check if there is data and if not redirect away from the page.
public function info( $x )
{
$details = $this->person_model->get_detail( $x );
if(empty($details))
redirect('other/url');
$data['body'] = "Personal_info";
$data['details'] = details;
$this->load->view('view', $data);
}
This way it doesn't throw errors and potentially attempt to display something that doesn't exist.
you can check if the passed id exists in database before trying to fetch related data, like:
$data_exists = $this->person_model->data_exists( $x );
if( $data_exists ) {
$data['details'] = $this->person_model->get_detail( $x );
$this->load->view('view', $data);
}
else {
//load some view for showing no such id exists in db
}
where data_exists() can be a function in model which returns TRUE or FALSE depending on existance of your id in database.

Sending $data Variable From Model To View

Okay, so I have this snippet of code in a controller. However, it's all DB driven and should really be in model - I get that. However, as you can see in the IF statement, I need to pass along $data to my view. Based on the outcome. I tried pasting this chuck of coding in a method in my model (calling the model method via controller), however the $data[update_prompt] string is not getting called by the view...
How would I translate this code into a model - sending the $data values back to my controller to embed in my view?
// show appropriate upgrade message if user has free account
$id = $this->session->userdata('user_id');
$this->db->select('subscription'); // select the subscription column
$this->db->where('id', $id); //find id in table that matches session id
$query = $this->db->get("subscriptions"); // connect to this database
$subscribe = $query->result_array(); //returns the result of the above
if($subscribe[0]['subscription'] == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
{
$data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
}
else
{
$data['update_prompt'] = '';
}
You would add a function in your model, like so:
public function myModelFunction($id) {
//we return row as we are looking up by primary key and are guaranteed only one row
return $this->db->select('subscription')
->where('id', $id)
->get('subscriptions')
->row();
}
Then, in your controller:
public function myControllerFunction() {
$subscribe = $this->my_model->myModelFunction($this->session->userdata('id'));
if($subscribe->subscription == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
{
$data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
}
else
{
$data['update_prompt'] = '';
}
}

Categories