codeigniter database array parsing - php

I am very new to code igniter so i may be doing this wrong but whatever. I am trying to display a database but the problem is there are multiple tables and each one varies in number of columns and column names.
foreach ($database as $value) {
print_r($value);
}
This prints off the entire array in a very sloppy way. I can parse out values if i have column names but since they vary, I am struggling to resolve a way to parse it.
example of the array (with 5 columns, ID, Brand, Model, Tested and Comment)
Array ( [ID] => 3 [Brand] => IBM [Model] => Thinkcentre 8215-E9U [Tested] => 1 [Comment] => )
Array ( [ID] => 1 [Brand] => MGP [Model] => Thinkcentre 8183-T6U [Tested] => 1 [Comment] => )
Array ( [ID] => 2 [Brand] => IBM [Model] => Thinkcentre 8215-22U [Tested] => 1 [Comment] => )
Array ( [ID] => 4 [Brand] => IBM [Model] => Thinkcentre 8215-W97 [Tested] => 1 [Comment] => )
Model
public function select_videocards() {
$this->load->database();
$query = $this->db->get('tbl_videocards');
return $query->result_array();
}
Controller
$table = NULL;
if($this->input->server('REQUEST_METHOD') == 'POST') { // POST has been received
$table = $this->input->post('table');
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$data['table'] = $table;
if($table!="select" AND $table!=NULL) {
echo $table;
$data['database'] = $this->Inventory_model->$table();
}

I just made more functions in my controller as wrapper functions and then made a new page for each table. worked perfectly.

Related

PHP SQLITE3 randomly not inserting data into database

I'm parsing a json file to add data to a sqlite database. It works fine apart from the fact that some entries I retrieve from the json file are just not added completely. As an example see this array I got from the json file:
(
[0] => Array
(
[Id] => 4215717
[Guid] => a2fd45b0-c602-4c82-bb30-19aba8bfacdf
[IsRawData] =>
[Name] => test 1
[State] => Released
[Created] => 2015-10-25T10:21:13Z
[CreatorId] => 65edfb59-8087-4f20-81d8-1dc7b94c5624
[Modified] => 2020-02-19T13:08:07Z
[ModifierId] => 65edfb59-8087-4f20-81d8-1dc7b94c5624
[EntryId] => 377794
[LanguageId] => Array
(
[PrimaryLangId] => 7
[SubLangId] => 1
)
)
[1] => Array
(
[Id] => 4215718
[Guid] => 4609ace8-8e6f-457d-a0ae-faa29950cdcb
[IsRawData] =>
[Name] => test 2
[State] => Released
[Created] => 2015-10-25T10:21:41Z
[CreatorId] => 65edfb59-8087-4f20-81d8-1dc7b94c5624
[Modified] => 2017-01-18T13:30:05Z
[ModifierId] => 65edfb59-8087-4f20-81d8-1dc7b94c5624
[EntryId] => 377794
[LanguageId] => Array
(
[PrimaryLangId] => 9
[SubLangId] => 1
)
)
)
For some entries I add to the db using the code below, I randomly only have the first entry from the array written to the db and I can't figure out a pattern for which entries it worked and for which ones it didn't.
Is there something wrong with my code? Or do you see any issues that could cause this behaviour?
// Prepare statement to propagate terms table
$termStmt = $o_db->prepare("INSERT INTO terms
(entryID, termID, term, status, wordclass, usage, type,
primaryLangID, secondaryLangID )
VALUES (:entryID, :termID, :term, :status, :wordclass, :usages, :types,
:primaryLangID, :secondaryLangID)");
// Bind term parameters
$termStmt->bindParam(':entryID', $i_entryID);
$termStmt->bindParam(':termID', $i_termID);
$termStmt->bindParam(':term', $s_term);
$termStmt->bindParam(':status', $s_status);
$termStmt->bindParam(':wordclass', $s_wordclass);
$termStmt->bindParam(':usages', $s_usage);
$termStmt->bindParam(':types', $s_type);
$termStmt->bindParam(':project', $s_project);
$termStmt->bindParam(':primaryLangID', $i_primaryLangID);
$termStmt->bindParam(':secondaryLangID', $i_secondaryLangID);
foreach ($a_entryData as $entry){
$entryID = $entry['entryID']; // entryID comes from another table in the db to get the full entry
$fullEntry = getEntry($entryID); //get entry from json
foreach ($fullEntry as $term){
foreach($term as $termEntry) {
$i_entryID = $termEntry['EntryId'];
$i_termID = $termEntry['Id'];
$s_term =$termEntry['Name'];
$s_status =$termEntry['State'];
$i_primaryLangID = $termEntry['LanguageId']['PrimaryLangId'];
$i_secondaryLangID = $termEntry['LanguageId']['SubLangId'];
// Now get the term properties and the corresponding values
$a_properties = getTermProperties($i_termID);
$a_propertyValues = propertyValues($a_properties);
$a_properties = getTermProperties($i_termID);
$a_values = propertyValues($a_properties);
if (isset($a_values['Wortklasse'])){
$s_wordclass = $a_values['Wortklasse'];
}else{
$s_wordclass = "N\A";
}
if (isset($a_values['Verwendung'])){
$s_usage = $a_values['Verwendung'];
}else{
$s_usage = "N\A";
}
if (isset($a_values['Benennungstyp'])){
$s_type = $a_values['Benennungstyp'];
}else{
$s_type = "N\A";
}
// Execute term statement and add data to the table
$termStmt->execute();
}
}
}
Thanks for your help :)

PHP function to update array value where part of array matches other part of array?

Let's say I need to update one of the [status] array values in the returned Array below.
In PHP I will get the array returned below into this variable $taskArray
The only thing I will have is the [taskid] of the Array item I need to modify and the new value for [status] that I would like to change it to.
I am looking for the most efficient way that I can take the array below, find the array that matches my [taskid] and change the [status] to my new status value and then return the complete updated array to a variable so I can pass it back to my database.
I'm really not sure how I can do that based on how the array is setup, I would appreciate any help in doing this please?
Based on this array below, I would like to basically pass in these 2 variable into a function and have the function make the updates mentioned above and return the whole updated array...
function updateTaskStatus($taskId, $newStatus){
// Contains the Array that is shown below this function
$tasksArray;
// Update $tasksArray [status] with the value of $newStatus
// WHERE $taskId is in the SAME array
// RETURN UPDATED $tasksArray
return $tasksArray;
}
// Calling function above would update the [status] to 'completed
// WHERE [taskid] = 4
updateTaskStatus(4, 'Completed');
Array
(
[0] => Array
(
[taskid] => 3
[name] => sdgsdfgdfg
[description] => dfgsdfgsdfg
[status] => In Progress
[priority] => Low
[type] => Magento
)
[1] => Array
(
[taskid] => 4
[name] => Dfgyrty
[description] => rtyrty
[status] => Open
[priority] => Urgent
[type] => Design
)
[2] => Array
(
[taskid] => 9
[name] => yrgrtyerty
[description] => rtyrt6yerty
[status] => Cancelled
[priority] => Urgent
[type] => Magento
)
[3] => Array
(
[taskid] => 9
[name] => ertgsdftg
[description] => dfgsdfg
[status] => Open
[priority] => Medium
[type] => SEO
)
[4] => Array
(
[taskid] => 30
[name] => fghdfgh
[description] => fghdfgh
[status] => In Progress
[priority] => Low
[type] => SEO
)
[5] => Array
(
[taskid] => 1410858495187
[name] => tyrty
[description] => tyrty
[status] => Open
[priority] => Low
[type] => Other
)
)
If I understood your question, the simple answer is to do a loop like this:
function updateTaskStatus($taskId, $newStatus){
global $tasksArray;
foreach($tasksArray as $k => $task)
{
if ($task['taskid'] == $taskId)
{
$tasksArray[$k]['status'] = $newStatus;
break;
}
}
return $tasksArray;
}
Note there is other solution (see php documentation with all array_* functions).
I added global to your code because otherwise this would not work, but using global is something to avoid everytime you can.
The easiest way to do this sort of thing is using a loop.
<?php
function updateTaskStatus($taskId, $newStatus){
// Loop through all the tasks to see if there's a match
foreach ($tasksArray as $id => $task) {
if ($task['taskid'] != $taskId) {
// Mismatch
continue;
}
$tasksArray[$id]['status'] = $newStatus;
}
// RETURN UPDATED $tasksArray
return $tasksArray;
}
You can do it like this:
foreach ($tasksArray as $task)
if ($task['taskid'] == $taskId)
$task['status'] = $newStatus;
Change key to task id and then use something like this
function updateTaskStatus($taskId, $newStatus){
$tasksArray[$taskId]['status'] = $newStatus;
}
updateTaskStatus(4, 'Completed');

CakePHP Model Query Return Data Formating

I'm looking for a way to make it so cake returns all database data in the same format/structure... Currently it returns two different types of format depending on the relationship.
If a model 'B' is associated with the current model 'A' being queried it will then place model associations for 'B' underneath it as you can see in [User] below. I want it so that all queries use that structure.
example:
$this->find('all', ....
returns:
Array
(
[0] => Array
(
[UserGroup] => Array
(
[id] => 53
[user_id] => 100003332014851
[media_id] =>
[name] => john
[description] => qwasdfad
)
[User] => Array
(
[id] => 100003332014851
[session_id] => ssm2qbrotmm13ho1ipm8ii2492
[username] =>
[password] => -1
[Planner] => Array
(
)
[Purchase] => Array
(
)
[Listing] => Array
(
)
)
)
I want this to look like:
Array
(
[0] => Array
(
[UserGroup] => Array
(
[id] => 53
[user_id] => 100003332014851
[media_id] =>
[name] => john
[description] => qwasdfad
[User] => Array
(
[id] => 100003332014851
[session_id] => ssm2qbrotmm13ho1ipm8ii2492
[username] =>
[password] => -1
[Planner] => Array
(
)
[Purchase] => Array
(
)
[Listing] => Array
(
)
)
)
)
)
In CakePHP, the find() method return data like your first format. But If you want to format like second one then you have to process it by hand (try to avoid this if possible)
$data = $this->find('all');
$assocs = Set::extract('/User', $data); // extracting all `User` array
foreach($assocs as $key => $assoc) {
unset($data[$key]['User']); // removing the associate `User` from `$data`
$data[$key]['UserGroup']['User'] = $assoc['User']; // adding associate under `UserGroup`
}
ended up doing this... it changes the output to what we need. The top level item does not have a header which is fine I just adjusted our scripts for that... maybe this will help somebody else if they need a custom idea
also no guarantee this covers all possible results but so far it works with all the queries we have.
class AppModel extends Model {
function afterFind($results, $primary) {
//if this is a primary, structure like a secondary so entire site is same format
if ($primary) {
$class = get_class($this);
//simple fix for primary
foreach ($results as $key => $result) {
$result = $this->formatData($result, $class);
$results[$key] = $result;
}
}
return $results;
}
function formatData($result, $class) {
$array = array();
if (isset($result[$class])) {
$array = $result[$class];
unset($result[$class]);
}
$array += $result;
return $array;
}
You can also use contain in this case along with find as UserGroup.User for your desired result

Cannot print data into "view"

I have a page that I would like to show the data from the database.
I can print_r($sale) and it shows the data that I am after - $sale is set in the controller but I cannot seem to do <?php $sale['name'] ?> it shows nothing.
Print_r:
Array ( [0] => stdClass Object ( [id] => 48 [name] => Jess McKenzie [location] => Auckland [bedrooms] => 5 [bathrooms] => 1 [condition] => Fair [description] =>
hii
[price] => 30.00000 [imagename] => purple.jpg [thumbname] => purple_thumb.jpg ) [1] => stdClass Object ( [id] => 49 [name] => jzmwebdevelopment [location] => Auckland [bedrooms] => 15 [bathrooms] => 4 [condition] => OK [description] =>
zebra
[price] => 25.00000 [imagename] => Zebra.jpg [thumbname] => Zebra_thumb.jpg ) )
Model:
function getSalesContent($id = NULL) {
$this->db->where('id', $id);
$query = $this->db->get('sales', 1);
if($query->num_rows() > 0) {
$row = $query->result_array();
return $row;
}else{
return FALSE;
} # End IF
} # End getSalesContent
It's returning an array of objects.
To show the first element returned you would use
$sale[0]->name;
To cycle through all of the values you could use a foreach loop
foreach($sale as $s){
print $s->name;
}
$query->result_array() returns an array of arrays, you would use $sale['name'] in a foreach loop.
$query->result() returns an array of stdclass objects, you would use $sale->name in a foreach loop.
I cannot seem to do $sale->name it
shows nothing.
Open your index.php file and add error_reporting(E_ALL) to the top. If you were error reporting you'd be able to see your mistakes with helpful error messages telling you exactly what went wrong. Just set it to 0 for when you go live.
I have tried <?php $sale['name'] ?> and get nothing
You need an echo statement: <?php echo $sale['name'] ?>
If $sale is the output you posted, <?php echo $sale[0]->name ?> should print Jess McKenzie

Cakephp: question about saveall() with multiselect

I'm wondering what the cleanest way is to implement a cakephp form where 1 control is a multi-select and the rest are text fields or single-selects, and then the data is inserted as multiple rows with a saveall(). So for example a form is selected with these values:
textfield A
value=Foo
mulit-select B
values=US,Mexico,Canada
single=select C
value=10
and so I want to insert these rows into the database with a saveall():
Foo,US,10
Foo,Mexico,10
Foo,Canada,10
Now I know in the add view I can use this format for the input statement:
input('Model.0.field1',...)
but I'm wondering if I can mix that in that same form with inputs formatted like
input('Model.field2',....).
Update:
When I mix and match the single-select and multiple-select controls, the form data gets submitted like this:
Array
(
[Alert] => Array
(
[schedule_id] => 75
[user_id] => 6
[0] => Array
(
[frequency] => Array
(
[0] => WEEKLY
[1] => MONTHLY
)
)
[limit_value] => .03
[limit_adjustment] => 0
[type] => LIMIT
[disabled] => 0
)
)
I tried passing that data into saveall() but it treats it like a single record.
Update2: I think saveAll() requires that the multiple rows of data be formatted like this:
Array
(
[Article] => Array(
[0] => Array
(
[title] => title 1
)
[1] => Array
(
[title] => title 2
)
)
)
So it looks like after the submit I'm going to need some javascript code that will restructure the array.
I have something that works... I'm not sure if it takes full advantage of all of cake's "automagic" capabilities, but I don't think it's too convoluted.
So I just added the following code to my controller's add function:
if (!empty($this->data)) {
//debug($this->data, true);
/* begin custom code */
$multiselect = $this->data['Alert']['entity_id'];
$tmp2 = array();
foreach ($multiselect as $item)
{
$tmp = $this->data['Alert'];
$tmp['entity_id'] = $item;
array_push($tmp2,$tmp);
}
$this->data['Alert'] = $tmp2;
debug($this->data,true);
/* end custom code */
$this->Alert->create();
//restructure data
if ($this->Alert->saveAll($this->data['Alert'])) {
$this->Session->setFlash(__('The alert has been saved', true));
//$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The alert could not be saved. Please, try again.', true));
}
and that converts my data to this:
Array
(
[Alert] => Array
(
[0] => Array
(
[schedule_id] => 74
[entity_id] => 1
[user_id] => 6
[frequency] => HOURLY
[limit_value] => .02
[limit_adjustment] => 0
[type] => LIMIT
[disabled] => 1
)
[1] => Array
(
[schedule_id] => 74
[entity_id] => 2
[user_id] => 6
[frequency] => HOURLY
[limit_value] => .02
[limit_adjustment] => 0
[type] => LIMIT
[disabled] => 1
)
)
)

Categories