Cakephp saving 10 new rows after checking id of the user - php

I'm trying to create 10 new rows in controller if the userid is not found in the user_id row. I tried create() function and then save() function but it doesn't seem to do the job.
Below is the code, is there a way we can solve this issue?
function invite_fellows(){
//Read userid
$userid = $this->Session->read('Auth.User.id');
$invite_table = $this->User->Invite->findbyUserId($userid);
if(empty($invite_table)){
$code_limit = 10;
//Save 10 unique codes for the user
for($i=0; $i<$code_limit;$i++){
$unique_id = $this->_unique($userid); // Unique id with userid as initial prefix
$this->data['Invite'] = array('user_id' => $userid, 'code' => $unique_id);
$this->User->Invite->create();
$this->User->Invite->save($this->data['Invite']);
}
}
//Find user in users and associated tables
$user = $this->User->findbyId($userid);
//Find user in invite table
$confirmed = $this->User->Invite->find('count', array('conditions' => array('user_id' => $userid,'invited_user >' => 0)));
$this->set(compact('user','confirmed'));
}
Thank you.

Most likely there's a validation rule that blocks the save. Try adding debug( $this->User->Invite->validationErrors ); after the save() to check for that. Make sure debug level is set to at least 1 in core.php.

Related

Database data field check before Data insertion

I have a data coming from the HTML Page. And i want to check whether the date and the place values already exists. If they exists, it should throw an error saying Data is already present, if those date and place data is not there it should allow the user to save it.
Here is the code which i have written to save it,
public function StoreSampling(Request $request)
{
$date = Carbon::createFromFormat('d-m-Y', $request->input('date'))->format('Y-m-d');
$doctorname = Input::get('doctorselected');
$product = Input::get('product');
$product= implode(',', $product);
$quantity = Input::get('qty');
$quantity =implode(',',$quantity);
$representativeid = Input::get('representativeid');
//Store all the parameters.
$samplingOrder = new SamplingOrder();
$samplingOrder->date = $date;
$samplingOrder->doctorselected = $doctorname;
$samplingOrder->products = $product;
$samplingOrder->quantity = $quantity;
$samplingOrder->representativeid = $representativeid;
$samplingOrder->save();
return redirect()->back()->with('success',true);
}
I searched some of the Stack over flow pages. And came across finding the existence through the ID And here is the sample,
$count = DB::table('teammembersall')
->where('TeamId', $teamNameSelectBoxInTeamMembers)
->where('UserId', $userNameSelectBoxInTeamMembers)
->count();
if ($count > 0){
// This user already in a team
//send error message
} else {
DB::table('teammembersall')->insert($data);
}
But i want to compare the date and the place. And if they are not present, i want to let the user to save it. Basically trying to stop the duplicate entries.
Please help me with this.
There are very good helper functions for this called firstOrNew and firstOrCreate, the latter will directly create it, while the first one you will need to explicitly call save. So I would go with the following:
$order = SamplingOrder::firstOrNew([
'date' => $date,
'place' => $place
], [
'doctorname' => Input::get('doctorselected'),
'product' => implode(',', Input::get('product')),
'quantity' => implode(',',Input::get('qty')),
'representativeid' => Input::get('representativeid')
]);
if($order->exists()) {
// throw error
return;
}
$order->save();
// success
You need to modify your query to something like this:
$userAlreadyInTeam = SamplingOrder::where('date', $date)
->where('place', $place) // I'm not sure what the attribute name is for this as not mentioned in question
// any other conditions
->exists();
if (userAlreadyInTeam) {
// Handle error
} else {
// Create
}
You do not need to use count() as your only trying to determine existence.
Also consider adding a multi column unique attribute to your database, to guarantee that you don't have a member with the same data and place.
The best way is to use the laravel unique validation on multiple columns. Take a look at this.
I'm presuming that id is your primary key and in the sampling_orders table. The validation rule looks like this:
'date' => ['unique:sampling_orders,date,'.$date.',NULL,id,place,'.$place]
p.s: I do not see any place input in your StoreSampling()

Programmatically create drupal user and then store UID of new user

I am attempting to create a new Drupal 7 user and then assign the UID of that user to a variable. I want to store this UID so that I can create a new node and assign that user as the owner.
QUESTION: Does anyone know how to get the UID of the newly created user?
MY CODE:
// CREATE USER
$newUser = array(
'name' => $refereeUsername,
'pass' => $refereePassword,
'mail' => $refereeEmail,
'status' => 1,
'init' => $refereeEmail,
'roles' => array(
2 => 'authenticated',
53 => 'Referer',
),
);
user_save($usera, $newUser);
// MY ATTEMPT TO GET THE NEWLY CREATED USER ID
$uidn = $usera->uid;
// CREATE NODE
$node = new stdClass;
$node->type = 'referee';
$node->title = 'Referee report for xx';
$node->uid = $uidn;
$node->status = FALSE;
$node->field_testff['und'][0]['value'] = "testworked";
node_object_prepare($node);
node_save($node);
user_save() returns the user object upon successful save (the variable is sent by value, not by reference). Try this:
$account = user_save($newUser);
$uidn = $account->uid;
To solve this issue I used the user_load_by_mail() function. Using the user_save() function caused an integrity constraint violation error in my code.
$accountb = user_load_by_mail($email);
$uidn = $accountb->uid;
Documentation:
https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_load_by_mail/7

How do I get the last id from a table after multiple insert

I am adding data to three tables, I needed to get the last ID of the first table to use in the second table, which was successful with $this->db->insert_id() function, Trying that with the second table still gives me the ID of the first table. The arrangement of my code is:
function addcrm() {
//Post data collection array from the webform form
$customerdata = array(
"salutation"=>$this->input->post('salutation'),
"mobilenumber"=>$this->input->post('mobilenumber'),
"emailaddress"=>$this->input->post('emailaddress')
);
$this->db->insert('api_customer', $customerdata);
$customer=$this->db->insert_id();
$leaddata = array(
"fieldrep"=>$this->input->post('fieldrep'),
"fk_customerID"=>$customer,
"te"=>$this->input->post('takage'),
"othercost"=>$this->input->post('othercost')
);
$this->db->insert('api_lead', $leaddata);
$leadID = $this->db->insert_id();
for ($i =0; $i<count($_POST['w_product']); $i++){
$productdata = array(
"name" => $_POST['w_product'][$i],
"type" => $_POST['w_type'][$i],
"cost" => $_POST['w_cost'][$i],
"fk_leadID"=> $leadID
);
$this->db->insert('api_prod',$productdata);
}
$url = base_url('cXXXXXXXXXXXXXX);
redirect($url);
}
You are missing something obviously in the second call. ;)
$customer = $this->db->insert_id();
$leadIdD = $this->db->insert_id;
See? :)
Try working with the following methods:
$this->db->start_cache(); // Before query
$this->db->stop_cache(); // After query
$this->db->flush_cache(); // Clear query
This way you make clear and flushed queries.
if you are using an auto increment table you may try using MYSQL_LAST_INSERT_ID();
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html

How to check records already exist in database when u save new record?

I want to add the new records in table if proudct_id and plan_id is already exist in same row then the error occur otherwise it save the record. I have written following lines of code but no success, if there is any help so please, thanks. I am doing it in cakephp
function admin_product_plan_add(){
$exists = $this->ProductPlan->find('all');
$this->set('exists',$exists);
foreach ($exists as $exists){
$plan_id = $exists['ProductPlan']['plan_id'];
$product_id = $exists['ProductPlan']['product_id'];
}
$conditions = array('ProductPlan.product_id' => $plan_id, 'ProductPlan.plan_id' => $product_id);
$data = $this->ProductPlan->find('all' , array('conditions'=>$conditions));
if (isset($data) && !empty($data))
{
echo '<p>User have already add this product plan!</p>';
}else{
if ($this->ProductPlan->save($this->data)){
$this->Session->setFlash('You have successfully add the product plan');
$this->redirect(array('controller' => 'productplans','action' => 'admin_product_plan_list'));
}
}
}
Use hasAny()
something like:
public function admin_product_plan_add(){
if($this->ProductPlan->hasAny(array("product_id" => $this->data['ProductPlan']['product_id'],'plan_id' => $this->data['ProductPlan']['plan_id']))){
// USER ALREADY HAVE THIS PRODUCTPLAN
} else {
//CREATE NEW PRODUCTPLAN
}
}
or something like that.
Hope this helps
One solution is to use a uniq index over these two rows. So when someone tries do add another row with the same data on these two rows, mysql throws an error and the data is not inserted.

User reporting Library

I would like to build (or find) a php reporting library that I can use to allow my users to report any type of content as bad. Actually, if they could report content as good (which I guess would mean a rating system) that would be even better. So if anyone knows of a library like this I would love to hear about it.
Anyway, this is how I imagine the database working and I would like to know if this sounds correct.
ID - ID of row
USER_ID - ID of the user voting/reporting
ITEM_ID - UNIQUE table row ID of the item reported (post, other user, link, etc...)
TYPE - the name of the table this pertains to (posts, users, links, etc...)
DATE - datetime of report
VALUE - I guess this could be an UP vote or DOWN vote
By including the [TYPE] column I can use this voting system across all content types on my site instead of just one (like forum posts). By storing the user_id I can be sure that only one vote/report is cast per item per user.
Well, I went ahead and built it like I said. Frank was right, it wasn't too hard. Here is the code incase anyone else wants to use it on a MVC that supports AR styled DB calls like CodeIgniter or MicroMVC:
/*
* Multi-table user voting model
*/
class votes extends model {
public static $table = 'votes';
function cast( $user_id = NULL, $item_id = NULL, $type = NULL, $vote = TRUE) {
$where = array(
'user_id' => $user_id,
'item_id' => $item_id,
'type' => $type
);
//Try to fetch this row
$row = $this->db->get_where(self::$table, $where );
//Look for an existing vote row
if( $row && ! empty($row[0]) ) {
//Fetch row
$row = $row[0];
//If they already voted this way... then we're done!
if( $row->vote == $vote) {
return;
}
//Else update the row to the new vote
$row->vote = $vote;
$row->date = convert_time(time());
$this->db->update( self::$table, $row, array('id' => $row->id) );
return;
}
//Else create a new vote for this item
$row = array(
'user_id' => $user_id,
'item_id' => $item_id,
'type' => $type,
'date' => convert_time(time()),
'vote' => $vote,
);
$this->db->insert( self::$table, $row);
}
}

Categories