I am inserting data to payments table where Ref column needs to be unique. In below code, with $ref=$_POST['PAYMENT_ID']; I am inserting always a new ref no with other column value in each post back. Sometimes it is posting duplicate ref no. I am trying to keep the ref no unique.
For this I have written following code.What I am trying to do is if existing Ref Column value doesn't match with new $ref=$_POST['PAYMENT_ID'] value then it will insert data.But it is not working and inserting ref no yet it is matched with new ref no.
How can I do this?
<?php
$ref=$_POST['PAYMENT_ID'];
$pending = "Pending";
$method = "Uploaded funds";
$today = date('Y-m-d');
$time=$_POST['TIMESTAMPGMT'];
$type = "Pm";
$table_payments = $wpdb->prefix . "payments";
$check=$wpdb->get_results("SELECT Ref FROM $table_payments");
$checkrows=mysqli_num_rows($check);
if ($checkrows!=$ref) {
if($hash2==$_POST['V2_HASH']){
$wpdb->insert( $table_payments, array(
'Method' => $method,
'Today' => $today,
'Time' => $time,
'Ref' => $ref,
'Batch' => $batch,
'Type' => $type,
'Status' => $pending,
'User' => $me
));}}
?>
The problem is, $Ref is a user's submitted value and $checkrows holds the total number of rows in $table_payments table. And that's why the condition if ($checkrows!=$ref) { ... is failing.
You have to change your SQL query and the subsequent code in the following way,
// your code
$table_payments = $wpdb->prefix . "payments";
$check=$wpdb->get_results("SELECT * FROM $table_payments WHERE Ref = '$ref'");
$checkrows=$wpdb->num_rows;
if ($checkrows == 0) {
// do INSERT operation
}
Moreover, you should make Ref column of your table unique
Related
I'm trying to pull the last inserted id from a database table so that I can input it into a new database table, like so:
$mealplaninput =
MealPlanInput::create([
'meal_type' => $meal,
'suitable_for' => $suited,
'allergens' => $allerg,
'specific_allergen' => $spec,
'no_of_people' => $nop,
'start_date' => $request->date,
'no_of_days' => $nod,
'user_id' => $currentuserid,
]);
The attempt to pull the last id (but doesn't work):
$uniquemealplanid = $mealplaninput->id();
To then input into new table:
MealPlanDisplay::create([
'MealPlan_ID' => $uniquemealplanid,
'Day' => $recipeday,
]);
However I get the error:
Call to undefined method App\Models\MealPlanInput::id()
I have tried other methods too, like:
$uniquemealplanid = $this->create($mealplaninput)->id;
But the error I get is:
Method App\Http\Controllers\MealPlanInputController::create does not exist.
How can I pull the last id from MealPlanInput?
You need to create an object from the model to get ID.
$mealplaninput = new MealPlanInput;
$mealplaninput->meal_type = $meal;
$mealplaninput->suitable_for = $suited;
$mealplaninput->allergens = $allerg;
$mealplaninput->specific_allergen = $spec;
$mealplaninput->no_of_people = $nop;
$mealplaninput->start_date = $request->date;
$mealplaninput->no_of_days = $nod;
$mealplaninput->user_id = $currentuserid;
$mealplaninput->save();
$uniquemealplanid = $mealplaninput->id;
you need to try
$uniquemealplanid = $mealplaninput->id;
insted of
$uniquemealplanid = $mealplaninput->id();
I have this function that doesn't batch insert to my database, I only used the batch insert function recently because back then I only used object inserts through for loops like this
$subject = ActiveCurriculum::find()
->select('scstock.*')
->joinWith('schead')
->where(['schead.TrNo' => $TrNo])
->one();
$activesubject = new ActiveSubject();
$activesubject->clientid = $clientid;
$activesubject->TrNo = $subject->TrNo;
$activesubject->LINE = $subject->LINE;
$activesubject->period = $subject->schead->period;
$activesubject->subjectcode = $subject->subjectcode;
$activesubject->schedday = $subject->schedday;
$activesubject->schedtime = $subject->schedtime;
//remember to use schead if the value is joined from another table.
$activesubject->section = $subject->schead->section;
$activesubject->roomcode = $subject->roomcode;
$activesubject->units = $subject->units;
$activesubject->save();
//reduces the slot of ccsubject by 1
$subject->slots = $subject->slots - 1;
//never forget the saving part
$subject->save();
I am not able to use this this time because I needed to insert an array of values so as I said I opted to this.
$subjects = ActiveCurriculum::find()
->select(['scstock.*', 'schead.*'])
->leftJoin('schead', 'schead.TrNo = scstock.TrNo')
->where(['sectiongroup' => $group])
->asArray()
->all();
// $activesubject = new ActiveSubject();
$bulkInsertArray = [];
foreach ($subjects as $values) {
$bulkInserArray[] = [
'clientid' => $clientid,
'TrNo' => $values['TrNo'],
'LINE' => $values['LINE'],
'period' => $values['period'],
'subjectcode' => $values['subjectcode'],
'schedday' => $values['schedday'],
'schedtime' => $values['schedtime'],
'section' => $values['section'],
'roomcode' => $values['roomcode'],
'units' => $values['units'],
];
if (count($bulkInsertArray) > 0) {
$columnNameArray = ['clientid', 'TrNo', 'LINE', 'period', 'subjectcode', 'schedday', 'schedtime', 'section', 'roomcode', 'units'];
// below line insert all your record and return number of rows inserted
$insertCount = Yii::$app->db->createCommand()
->batchInsert('subjectcontainer', $columnNameArray, $bulkInsertArray)
->execute();
}
}
But I am not able to
$subject->slots = $subject->slots - 1;
$subject->save();
like in the first one because of the arrays, can you tell me how to do this in my second code because I need to subtract the slots column by 1 every iteration of the for loop this time. Thank you.
You can perform subtraction using single query. Something like this:
$columnToUpdate = ['slots' => new \yii\db\Expression('[[slots]] - 1')];
$condition = ['sectiongroup' => $group];
ActiveCurriculum::updateAll( $columnToUpdate, $condition );
It will execute SQL:
UPDATE `active_curriculum` SET `slots`=`slots` - 1 WHERE `sectiongroup`=1234
You just need to make correct condition that correctly selects necessary rows. Alternatively, you can collect primary keys of records (IDs) when you prepare $bulkInserArray and use them for condition:
$condition = ['id' => $subjectIDsToUpdate];
This condition will build id IN (...) automatically.
I try to insert data to a table in CI 3 that has fields as below:
pageid is auto increment and I write code in model as this:
$data = array(
'title'=>$title,
'description'=>$des,
'url'=>'page/view/'.pageid
);
$this->db->insert('page',$data);
The problem is that the pageid is unknown as the field name. What should I do because I want to concatenate pageid to url?
You need two query for it
1)You need to insert title and description first and get last page id from database
$data = array(
'title' => $title,
'description' => $des
);
$this->db->insert('page', $data);
$page_id = $this->db->insert_id();// get last pageid
2)Update url second
$data = array(
'url' => 'page/view/'.$page_id
);
$this->db->where('pageid'$page_id);// update with page id
$this->db->update('page', $data);
OK so you can add all data first then after insert just update the url
field.
$data = array(
'title' => $title,
'description' => $des,
'url'=>'page/view/'
);
$this->db->insert('page', $data);
$page_id = $this->db->insert_id();
2)Now update URL
$update= array(
'url' => 'page/view/'.$page_id
);
$this->db->where('page_id'$page_id);
$this->db->update('page', $update);
Hope this will help you
Common & Easy Method
Goto
Phpmyadmin
select your database, then go to page table.
Click structure on top.
Click Change, in front of id field.
Then there is check box with AI(Auto Increment)
Check that and click save
If with code(use this)
public function FunctionName()
{
$query = $this->db->query("SELECT id FROM pages ORDER BY id DESC LIMIT 1");
$result = $query->result_array();
$id = $result['id']; // or some times $result[0]['id']
$data = array(
'title' => $title,
'description' => $des,
'url' => 'page/view/'.pageid,
'id' => $id
);
$this->db->insert('page',$data);
}
Just do like this:
$data = array(
'title'=>$title,
'description'=>$des
);
$this->db->insert('page',$data);
$page_id = $this->db->insert_id();
//To pass page_id to url column
$this->db->where('page_id', $page_id);
$data_1 = array('url'=>'page/view/'.$pageid);
$this->db->update('page', $data_1);
You can first get the highest Auto-Incremented id from select query and then, Use insert query for inserting the new row.
eg.
$id = $this->db->query("Select max(page_id) AS page_id from pages");
if($id->num_rows() > 0){
$result = $id->result_array();
$page_id = $result[0]['page_id'] +1;
}
// if table is empty
else{
$page_id = 1;
}
$data = array(
'title' => $title,
'description' => $des,
'url'=>'page/view/'.$page_id );
$this->db->insert('page',$data);
Please check it image for add auto increment id in phpmyadmin.
I'm having an issue using the Quickbase API to perform the following:
SELECT 1, 2, 3 FROM table AA that has column BB = 1
foreach record {
Insert 1, 2, 3 into table ZZ.
}
function add_children($opportunity_id) {
global $config;
$qbc = new QuickBase($_SESSION['qb_username'] ,
$_SESSION['qb_password'],
true,
$config['AA'],
$config['debug'],
$config['app_token']);
$xml = $qbc->do_query("{'" . $config['AA'] . "'.EX.''}", 0, 0, 'a', 0, '', '');
$records = array();
foreach($xml->record as $record) {
$r = array();
$r['record_id'] = $record->record_id_;
$r['account_number'] = $record->account_number;
$records[] = $r;
$xml = $qbc->add_record($records[]);
}
}
First, I'm assuming that you're using this PHP SDK by QuickbaseAdmirer https://github.com/QuickbaseAdmirer/QuickBase-PHP-SDK. There are a few potential problems with your code.
Double check that your constructor is correct. Unless you've modified it, the Quickbase constructor in the SDK (again that I'm assuming you're using) takes user name, password, xml, database id, and then token in that order. Whatever value is in $config['debug'] may be taken as the token and the value of $config['app_token'] may be taken as your realm. Also, $config['AA'] as used in the constructor should be a string of random seeming characters like "bbqn1y5qv". Here's the constructor in the SDK for reference:
public function __construct($un, $pw, $usexml = true, $db = '', $token
= '', $realm = '', $hours = '')
Your query $xml = $qbc->do_query("{'" . $config['AA'] . "'.EX.''}", 0, 0, 'a', 0, '', ''); is not returning any records because $config['AA'] is both being used as your DBID (in the constructor) and your field ID in the query. The DBID must be a string and the field ID must be an integer that corresponds to the field you're making the query for. For example, if you wanted to return records created today your query would be '{1.IR.today}' because 1 is always the field ID for date created. It's also not returning any records because the SDK requires queries be passed as an array of arrays. So, my records created today query needs to be rewritten as:
$query= array(
array(
'fid' => '1',
'ev' => 'IR'),
'cri' => 'today'),
);
You'll also need to pass a string of period separated values to the clist parameter of the method or leave it blank for the table defaults. For example, if I wanted to get the date created and record ID for all records in this table sorted by date ascending, I would use this:
$query= array(
array(
'fid' => '3',
'ev' => 'GT'),
'cri' => '0'),
);
$xml = $qbc->do_query($query, '', '', '1.3', '1', '', 'sortorder-A');
You can read up more on the Quickbase API, and do_query specifically, here http://www.quickbase.com/api-guide/index.html#do_query.html
The add record API call takes pairs of field IDs and values. The SDK handles that by taking an array of arrays with 'fid' and 'value' pairs. Assuming you want to put the value of $record->record_id_ in field #37 and $record->account_number in field #30 your code should look like this:
foreach($xml->record as $record) {
$records= array(
array(
'fid' => '37', //Whatever field you want to store the value to
'value' => $record->record_id_),
array(
'fid' => '30',
'value' => $record->account_number),
);
$xml = $qbc->add_record($records);
}
Throw in a print_r($xml); at the end and you can see any response from Quickbase for debugging. You should get something like this for a success:
SimpleXMLElement Object ( [action] => API_AddRecord [errcode] => 0 [errtext] => No error [rid] => 81 [update_id] => 1436476140453 )
The way your code is presented, you may not get the results you expect. Your do query and add record method calls are performed on the same table and that isn't normally what someone would want. Usually, the goal is to perform a do query on one table and then use that data to add records in a different table. If that's the case, you'll need to change the database ID in your $qbc object before you preform the add record call. This is easy enough to do with $qbc->set_database_table('DBID'); where DBID is the target table ID (which should be a string of random seeming characters like "bbqn1y5qv").
Best of luck!
This is my function to insert new rows to a table, depending on the date. I want to avoid duplication of rows if one already exists. This function basically inserts November, 2014 as mwf_month, so mwf_student_id and mwf_month pairs are unique for the row. What modification should I do to avoid this kind of duplication?
public function month_wise_due($grade_due, $new_due, $id, $remaining) {
$now1 = time();
$now = date('F, Y', $now1);
$store = array(
'mwf_month' => $now,
'mwf_previous' => $remaining,
'mwf_due' => $grade_due,
'total_due' => $new_due,
'mwf_student_id' => $id,
'mwf_pay_day' => 'Not Yet Paid',
'mwf_payment' => 0,
'mwf_diff' => $new_due
);
$this->db->trans_start();
$this->db->insert('mwf', $store);
$this->db->trans_complete();
}
The right way is to update your database table by adding "unique key" on two fields "mwf_month+mwf_student_id". The SQL command to do it is:
ALTER TABLE `mwf` ADD UNIQUE `unique_month_student`(mwf_month,mwf_student_id);
Then, possible duplicity would end with SQL error you can catch. You can also suppress the exception with 'ignore' statement or use 'replace' method instead of 'insert'.
If you don't have needed privileges on the table, you would need to simply check whether the pair exist with separate sql call before inserting new record.
I have found a solution from some where else without altering the table, it seems good to me.
$now1 = time();
$now = date('F, Y', $now1);
$row_exists = "SELECT * FROM mwf WHERE mwf_month = '" . $now."' AND mwf_student_id = '" . $id."' LIMIT 1";
if ( ! $this->db->simple_query($row_exists)) {
$store = array(
'mwf_month' => $now,
'mwf_previous' => $remaining,
'mwf_due' => $grade_due,
'total_due' => $new_due,
'mwf_student_id' => $id,
'mwf_pay_day' => 'Not Yet Paid',
'mwf_payment' => 0,
'mwf_diff' => $new_due
);
$this->db->trans_start();
$this->db->insert('mwf', $store);
$this->db->trans_complete();
}