Quickbase delete_record - quickbase

I am unable to get delete_record function to work. Here is the delete_record code that I am currently using:
$qb->db_id = $myQbTables["table1"]; //using table 1 now
$queries = array( //this is the where clause now for the delete query
array(
'fid' => '12',
'ev' => 'EX',
'cri' => '1175'
),
array(
'fid' => '8',
'ev' => 'EX',
'cri' => $Child_ID
)
);
$results = $qb->do_query($queries, '', '', 'a', '1', 'structured', 'sortorder-A'); //get all results
if($results->errCode !== 0) {
echo $results->errTxt;
}
print_r($results);
foreach($results->table->records->record as $record){ //getting results of delete query
$Deletevar = $record->f[11];
$deleted = $qb->delete_record($Deletevar); //deleting results
print_r($deleted);
}
I know that the 'cri' matches things in my quickbase but I can't seem to use f[3] (the record id) to delete it!
NOTE
I have found the main issue I was having! If you are making API calls using the QB API, delete records and purge records does not include the app token!! Please use the following code to update the delete_records function!!!!
public function delete_record($rid) {
if($this->xml) {
$xml_packet = new SimpleXMLElement('<qdbapi></qdbapi>');
$xml_packet->addChild('rid',$rid);
$xml_packet->addChild('ticket',$this->ticket);
$xml_packet->addChild('apptoken',$this->app_token);
$xml_packet = $xml_packet->asXML();
$response = $this->transmit($xml_packet, 'API_DeleteRecord');
}
else {
$url_string = $this->qb_ssl . $this->db_id. "?act=API_DeleteRecord&ticket=". $this->ticket
."&apptoken=".$this->app_token."&rid=".$rid;
$response = $this->transmit($url_string);
}
return $response;
}

I think you may be missing something in your query. If you're trying to get a list of records where the field 12 is 1157 and field 8 is equal to $Child_ID you'll need to add AND into your query. When using the API in a URL the query would be &query={12.EX.1175}AND{8.EX.77} if, for example, the child ID were 77. To do that in the PHP SDK for Quickbase you add 'ao' => 'AND' to all arrays following the first query array. Try updating your $queries array to this:
$queries = array( //this is the where clause now for the delete query
array(
'fid' => '12',
'ev' => 'EX',
'cri' => '1175'
),
array(
'ao' => 'AND', // Saying that 12.EX.1175 AND 8.EX.$Child_ID
'fid' => '8',
'ev' => 'EX',
'cri' => $Child_ID
)
);
My PHP skills aren't particularly good, but you'll need to do a bit more to get the record ID#. In the original code, I think that $record->f[3] will just return to SimpleXMLObject for the third field in the array. That won't necessarily be field ID 3 (the record ID). You can either choose to not use the structured format (and change all of your code to match) or add a loop that goes through all the fields and deletes when it reaches the field with id 3:
foreach($results->table->records->record as $record){ //getting results of delete query
//Loop through all fields to find id 3
foreach($record->f as $field){
if($field['id'] == "3"){
$Deletevar = $field['id'];
$deleted = $qb->delete_record($Deletevar); //deleting result
print_r($deleted);
break; //Stops this loop since FID 3 was found
}
}
}
Some performance notes: If you aren't using any other fields, you can set your query to only return record IDs by passing a clist that is just '3'. Also, each delete_record() is a separate API call. There is another method purge_records that allows you pass a query and Quickbase deletes all of the records that match your query. You may want to look into using purge_records() because you can you use it in place of your do_query() and avoid all the loops. It uses fewer of your resources and Quickbase's to process as well.

Related

Pass data from controller to View in Laravel

I have a query that I am not able to pass to the view.
$dias_usados = calendario::where('id_funcionario', '=', $userid)
->groupBy('id_funcionario')
->sum('contaferias');
dd outputs the correct expected value.
I tried to pass to the View as follows:
return view(
'ausencia',
compact('tabela'),
['itens' => $ferias],
['dias_usados' => $dias_usados]
);
I'm having problems with the last one dias_usados. The first two work normally.
<h3>{{$dias_usados}}</h3>
Causes the following error:
Undefined variable: "dias_usados"
I also leave the path I have on the route, but I don't see anything wrong
Route::get('Ausencia', [AusenciaController::class, 'index'])->name('ausencia.index');
This is the the definition of the view helper
function view($view = null, $data = [], $mergeData = []) { }
You are misusing the function by giving it three separate arrays expecting it to get them as $data.
Fixes
return view('ausencia', [
'tabela' => $tabela,
'itens' => $ferias,
'dias_usados' => $dias_usados,
]);
return view('ausencia')
->with(compact('tabela'))
->with(['itens' => $ferias])
->with(['dias_usados' => $dias_usados]);
return view(
'ausencia',
array_merge(
compact('tabela'),
['itens' => $ferias],
['dias_usados' => $dias_usados]
)
);

Laravel: How do I insert a multidimensional array in the controller

Table:
this is the table being used from the SQL database (id is auto incremented)
Array:
then output below is from the console of the browser after adding in: dd($replies);
The screenshot below shows the input of the ui, which is the same data registered in the array in the screenshot above
Entities:
The function below is being used to create/insert the data
public function create($payload_reply)
{
return rescue(function() use($payload_reply){
return self::insert($payload_reply);
});
}
Controller:
My issue is with my code below
if($result){
$replies = $request->get('reply');
dd($replies);
$payload_reply = [];
foreach($replies as $reply){
$payload_reply = [...$payload_reply, [
'id' => $request->get('group_id'),
'message_id' => $request->get('message_id'),
'parent_id' => $request->get('message_id'),
'reply' => $request->get('reply'),
'reply_type' => $request->get('reply_type'),
'reply_description' => $request->get('reply_description')
]];
}
$result = $this->bbrMessageTemplate->create($payload_reply);
}
This code does not insert the array in my table. I tried a for each loop in order for each data to be inserted one at a time until all have been inserted. What did I do wrong? I am not sure if it is the array or the for each.
Any help would be appreciated.
Clarifications: my variable $result works fine, so it leads to this if statement which is my main issue.

Laravel 6 validate multiple columns

Using the following code to create and update records with Laravel 6, how to add a unique validation that combines 'iso' and 'division' columns must unique, for both update and create? Also how to update the 'updated_at' column automatically without 'touch' it?
public function upsert(Request $request)
{
$this->authorize('manage','App\Admin\Division');
$this->validate($request,[
'records.iso' => 'required|regex:/^[A-Z]{2}$/',
'records.division' => 'required|min:2|max:3',
'records.remarks' => 'min:2|max:255|string|nullable',
],
[ 'records.iso.required'=>'Country iso Requied',
'records.iso.regex'=>'Country iso format : AA',
'records.division.required'=>'Division Code must entered',
'records.division.min'=>'Division Code minimum 2 characters',
'records.division.max'=>'Division Code maximum 3 characters',
],
);
$validatedData = $request->records;
if($validatedData['id']){ // have id, old record -> update
Division::where('id', $validatedData['id'])->update($validatedData);
//*******/ To correct updated_at no auto updated
$results = Division::find($validatedData['id']);
$results->touch();
//****** */ End of correction
}else{ // no id -> create record
$validatedData['auth'] = Auth::id();
$results = Division::create($validatedData);
}
return ['divisions' => $results];
}
All the validation rules apply for each field, i think you can do a foreach to workaround and compact the code, something like:
foreach ($records as $key => $record) {
$fields['record'.$key] = 'iso', 'division';
$rules['record'.$key] = 'required|min:2';
}
$validator = Validator::make($fields, $rules);
In the rules array you can put all the shared rules, but you have to create the other complex validation rules after this, so i think that your validation now is just fine.
And with the updated_at field, use the updateOrCreate
$results = Division::updateOrCreate(
['id', $validatedData['id'],
[$validatedData]
);
Adapt the above example for your code.

Yii2 ActiveRecord

I'm new to Yii and struggling to get my head around a few things.
I have model with this function:
public static function findNonGeo()
{
$query = new CallerIdentityQuery(get_called_class());
$query->select([
'cidref', 'caller_id', 'expiry', 'conf_call',
'type', 'redirect', 'destination', 'status', 'start_date',
'statusDesc' => new \yii\db\Expression("CASE status
WHEN 0 THEN 'Deactivated'
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Inactive'
WHEN 3 THEN 'Unregistered'
ELSE 'Permanently Deleted' END")])
->where(['status' => '1'])
->andWhere(['type' => 'N'])
->andWhere(['custref' => Yii::$app->user->identity->typedIdentity->getId()]);
return $query;
}
And in my controller I call this method like so:
$model = CallerIdentity::findNonGeo()->where(['cidref' => $id])->one();
but when the data is returned its like its just ignoring the
->andWhere(['type' => 'N'])
because I can view records that aren't of type 'N'.
so I'm having to do in my controller, maybe I'm doing something wrong or just not understanding it but I don't get it:
$model = CallerIdentity::findNonGeo()->where(['cidref' => $id])->andWhere(['type'=>'N'])->one();
another thing when using findOne($id):
$model = CallerIdentity::findOne($id);
null is returned.
Would appreciate any form of explanation/info.
When using where you're setting the where part of the query, not adding to it. So in the findNonGeo function you're building the required where parts. But with CallerIdentity::findNonGeo()->where(['cidref' => $id]) you're removing the already added where parts.
Try like this:
CallerIdentity::findNonGeo()->andWhere(['cidref' => $id])->one();
by using andWhere you'll keep the other parts and just add another one to it.

CodeIgniter ActiveRecord problems

I'm trying to build my first app on CodeIgniter. This is also my first time trying to stick to OOP and MVC as much as possible. It's been going ok so far but now that I'm trying to write my first model I'm having some troubles. Here's the error I'm getting:
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Castledine' at line 3
SELECT * FROM (authors) WHERE author = Earle Castledine
Which, as you'll see below, relates to the following line in my model:
$this->db->get_where('authors', array('author' => $author));
I'm not quite sure why it's throwing the error. Is it because Earle Castledine isn't in quotes? If so, why doesn't CI put them in there? I would doubt that's the issue, rather to think it's my fault, but I'm not sure.
I'm having another issue as well. Neither tags nor authors are getting inserted into their respective tables. Their insert statement is wrapped in a conditional that's supposed to be making sure they don't already exist, but it seems to be failing and the insert never happens. I assume it's failing because the tags aren't getting put in the database and it's down in the author section before it tosses the error. I know how to do this with pure PHP but I'm trying to go about doing it the pure CI ActiveRecord way.
Here's the statement I'm using:
if ($this->db->count_all_results() == 0)
And I'm using that instead of what I'd normally use:
if (mysql_num_rows() == 0)
Am I doing it wrong?
Here are my model and controller (only the functions that matter), commented as best I could.
Model:
function new_book($book, $tags, $authors, $read) {
// Write book details to books table
$this->db->insert('books', $book);
// Write tags to tag table and set junction
foreach ($tags as $tag) {
// Check to see if the tag is already in the 'tags' table
$this->db->get_where('tags', array('tag' => $tag));
// trying to use this like mysql_num_rows()
if ($this->db->count_all_results() == 0) {
// Put it there
$this->db->insert('tags', $tag);
}
// Set the junction
// I only need the id, so...
$this->db->select('id');
// SELECT id FROM tags WHERE tag = $tag
$query = $this->db->get_where('tags', array('tag' => $tag));
// INSERT INTO books_tags (book_id, tag_id) VALUES ($book['isbn'], $query->id)
$this->db->insert('books_tags', array('book_id' => $book['isbn'], 'tag_id' => $query->id));
}
// Write authors to author table and set junction
// Same internal comments apply from tags above
foreach ($authors as $author) {
$this->db->get_where('authors', array('author' => $author));
if ($this->db->count_all_results() == 0) {
$this->db->insert('authors', $author);
}
$this->db->select('id');
$query = $this->db->get_where('authors', array('author' => $author));
$this->db->insert('authors_books', array('book_id' => $book['isbn'], 'author_id' => $query));
}
// If the user checked that they've read the book
if (!empty($read)) {
// Get their user id
$user = $this->ion_auth->get_user();
// INSERT INTO books_users (book_id, tag_id) VALUES ($book['isbn'], $user->id)
$this->db->insert('books_users', array('book_id' => $book['isbn'], 'user_id' => $user->id));
}
}
Controller:
function confirm() {
// Make sure they got here by form result, send 'em packing if not
$submit = $this->input->post('details');
if (empty($submit)) {
redirect('add');
}
// Set up form validation
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<h3 class="error">', ' Also, you’ll need to choose your file again.</h3>');
$this->form_validation->set_rules('isbn','ISBN-10','trim|required|exact_length[10]|alpha_numeric|unique[books.isbn]');
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('tags','tags','required');
// Set up upload
$config['upload_path'] = './books/';
$config['allowed_types'] = 'pdf|chm';
$this->load->library('upload', $config);
// If they failed validation or couldn't upload the file
if ($this->form_validation->run() == FALSE || $this->upload->do_upload('file') == FALSE) {
// Get the book from Amazon
$bookSearch = new Amazon();
try {
$amazon = $bookSearch->getItemByAsin($this->input->post('isbn'));
} catch (Exception $e) {
echo $e->getMessage();
}
// Send them back to the form
$data['image'] = $amazon->Items->Item->LargeImage->URL;
$data['content'] = 'add/details';
$data['error'] = $this->upload->display_errors('<h3 class="error">','</h3>');
$this->load->view('global/template', $data);
// If they did everything right
} else {
// Get the book from Amazon
$bookSearch = new Amazon();
try {
$amazon = $bookSearch->getItemByAsin($this->input->post('isbn'));
} catch (Exception $e) {
echo $e->getMessage();
}
// Grab the file info
$file = $this->upload->data();
// Prep the data for the books table
$book = array(
'isbn' => $this->input->post('isbn'),
'title' => mysql_real_escape_string($this->input->post('title')),
'date' => $amazon->Items->Item->ItemAttributes->PublicationDate,
'publisher' => mysql_real_escape_string($amazon->Items->Item->ItemAttributes->Publisher),
'pages' => $amazon->Items->Item->ItemAttributes->NumberOfPages,
'review' => mysql_real_escape_string($amazon->Items->Item->EditorialReviews->EditorialReview->Content),
'image' => mysql_real_escape_string($amazon->Items->Item->LargeImage->URL),
'thumb' => mysql_real_escape_string($amazon->Items->Item->SmallImage->URL),
'filename' => $file['file_name']
);
// Get the tags, explode by comma or space
$tags = preg_split("/[\s,]+/", $this->input->post('tags'));
// Get the authors
$authors = array();
foreach ($amazon->Items->Item->ItemAttributes->Author as $author) {
array_push($authors, $author);
}
// Find out whether they've read it
$read = $this->input->post('read');
// Send it up to the database
$this->load->model('add_model', 'add');
$this->add->new_book($book, $tags, $authors, $read);
// For now... Later I'll load a view
echo 'Success';
}
}
Could anyone help shed light on what I'm doing wrong? Thanks much.
Marcus
Where you are using count_all_results(), I think you mean to use num_rows(). count_all_results() will actually create a SELECT COUNT(*) query.
For debugging your problems...
If you want to test if an insert() worked, use affected_rows(), example:
var_dump($this->db->affected_rows());
At any point you can output what the last query with last_query(), example:
var_dump($this->db->last_query());
You can also turn on the Profiler so you can see all the queries being run, by adding in the controller:
$this->output->enable_profiler(TRUE);
I managed to figure this out on my own. The controller didn't really change, but here's the new model:
function new_book($book, $tags, $authors, $read) {
// Write book details to books table
$this->db->insert('books', $book);
// Write tags to tag table and set junction
foreach ($tags as $tag) {
// Check to see if the tag is already in the 'tags' table
$query = $this->db->get_where('tags', array('tag' => $tag));
// trying to use this like mysql_num_rows()
if ($query->num_rows() == 0) {
// Put it there
$this->db->insert('tags', array('tag' => $tag));
}
// Set the junction
// I only need the id, so...
$this->db->select('id');
// SELECT id FROM tags WHERE tag = $tag
$query = $this->db->get_where('tags', array('tag' => $tag));
$result = $query->row();
// INSERT INTO books_tags (book_id, tag_id) VALUES ($book['isbn'], $query->id)
$this->db->insert('books_tags', array('book_id' => $book['isbn'], 'tag_id' => $result->id));
}
// Write authors to author table and set junction
// Same internal comments apply from tags above
foreach ($authors as $author) {
$query = $this->db->get_where('authors', array('author' => mysql_real_escape_string($author)));
if ($query->num_rows() == 0) {
$this->db->insert('authors', array('author' => mysql_real_escape_string($author)));
}
$this->db->select('id');
$query = $this->db->get_where('authors', array('author' => mysql_real_escape_string($author)));
$result = $query->row();
$this->db->insert('authors_books', array('book_id' => $book['isbn'], 'author_id' => $result->id));
}
// If the user checked that they've read the book
if (!empty($read)) {
// Get their user id
$user = $this->ion_auth->get_user();
// INSERT INTO books_users (book_id, tag_id) VALUES ($book['isbn'], $user->id)
$this->db->insert('books_users', array('book_id' => $book['isbn'], 'user_id' => $user->id));
}
}

Resources