Again I find myself at the mercy of the stackoverflow community!
I've gone over to use CodeIgniter for my PHP projects and it's been a breeze so far, hoever I've gotten stuck trying to update a database field with some post data.
My array is the usual: array(name => value, name => value, name => value);
which again is populated from the submitted $_POST data.
Similarly to the array, I have a database table with 2 fields: setting and value, where the names under setting corresponds to the array keys and value to the array keys' value.
(Did I explain that right?)
Nonetheless, I've been trying for a little while now to get this to work as it should, but, I'm really just waving my hands around in the dark.
I hope some of you bright minds out there can help me with this annoying issue!
Edit:
Thanks to everyone who replied! I managed to produce the result that I wanted with the following code:
foreach ($form_data as $key => $val)
{
$this->db->where ('setting', $key);
$this->db->set ('value', $val);
$this->db->update ('recruitment');
}
Now, I tried following up with this by adding:
if ($this->db->affected_rows() >= '1') { return true; }
return false;
To my model, and
if ($this->RecruitmentSettings->Update($form_data) == TRUE)
{
redirect('recruitment/success');
}
to my controller, but it's not working as expected at all. Any ideas what I'm doing wrong?
There are a lot of questions here. Do you already have values in the database and you want to update them? Or do you want to put in new data every time? The answer depends on that.
What you want is the insert_batch() or update_batch() methods of the active record class (if that's what you're using for the db).
foreach($post_array as $key => $value)
{
$settings[] = array(
'setting' => $key,
'value' => $value
);
}
$this->db->insert_batch('your_db_table', $settings);
OR, for updates:
$this->db->update_batch('your_db_table', $settings, 'setting');
You could do a query to check for settings and do insert_batch or update_batch depending on if there are results. If you wanted to insert every time, you could delete the rows in the table before you do the insert. I wouldn't do that without a transaction, however.
So you want to store the array data in the database? You could do this
Model
foreach ($data as $key => $item)
{
$this->db->set ('setting', $key);
$this->db->set ('value', $item);
$this->db->insert ('table_name');
}
return ($this->db->affected_rows() > 0);
Controller
if ($this->RecruitmentSettings->Update($form_data))
{
redirect('recruitment/success');
}
else
{
echo "error";
}
Related
I have a project that I need to finish before July, it's for school.
It was all going well until I started having problems with an array that comes from my database.
Please keep in mind that this is my first time with PHP and I'm learning as I am doing:
My database has a table named "Pessoas" and another named "Pessoas_Pessoas". The second was to keep the record of relationships between entries on the "Pessoas" table ( for example, if the ID 1 had a relationship with the ID 2, the information would be kept on "Pessoas_Pessoas" ).
The tricky part is that I am supposed to use PHP to prevent the user from duplicating a relationship.
A good example would be Facebook's friend system:
If I would be friend's with John, it wouldn't appear his profile on the "People you might know" section.
Since I am using MVC and Slim Framework, I managed to get what I want from the database on the model, but I have this problem on the Controller:
This is an image from the table "Pessoas_Pessoas", being id_PessoasA the id of the profile being visualized and id_PessoasB the id of the profile I'm trying to make a relationship with
I managed to get 5 profiles to test this feature and I managed to get those relationships as well, but the problem is that when I try to verify if the id of each profile is the same has id_PessoasB to then unset from the array, but it only works one time even if the condition is true. Here's the code:
foreach ($resultadoRelacao as $key => $value) {
foreach ($resultadoRelacao0 as $key0 => $value0) {
if ($value0['id'] == $value['id_PessoasB']) {
$indice = array_search($value0['id'], $resultadoRelacao0);
unset($resultadoRelacao0[$indice]);
}
}
}
Thanks for your time and please ask anything if needed. I'm not really sure what's needed anymore, I'm stuck for 2 weeks.
As you are using the foreach() to go through the array and you have matched the element against the one your looking for, you can then use the key value (in this case $key0) of the foreach() to remove the element your currently looking at...
foreach ($resultadoRelacao as $key => $value) {
foreach ($resultadoRelacao0 as $key0 => $value0) {
if ($value0['id'] == $value['id_PessoasB']) {
unset($resultadoRelacao0[$key0]);
}
}
}
foreach ($resultadoRelacao as $key => $value) {
foreach ($resultadoRelacao0 as $key0 => $value0) {
if ($value0['id'] == $value['id_PessoasB']) {
if(($indice = array_search($value0['id'], $resultadoRelacao0)) !==false){
unset($resultadoRelacao0[$indice]);
}
}
}
}
I am pulling an array of line items from an invoice:
private function lineItemsFromInvoice($xeroInvoice) : array
{
$lineItems = array();
foreach($xeroInvoice[XeroKeys::_XERO_INVOICE_KEY_LINE_ITEMS] as $value) {
array_push($lineItems, $value);
}
return $lineItems;
}
Following this, they are being inserted into a DB via:
foreach($this->lineItems() as $invoiceLineItem) {
...some SQL INSERT STATEMENT
}
I need to be able to query the line items and keep them in the order they were inserted. Further, the invoice itself can be updated, and line items inserted at any arbitrary position in the array. This order the items are sorted in the query needs to reflect this.
I could use a time stamp and ORDER BY and ensure that each line item is updated every time the INSERT statement is run.
I could also use an $index = 0 and $index++ in the lineItemsFromInvoice() function and add a Key => Value pair to the array and insert that as part of each LineItem but this seems messy. I don't know about an array() with:
Array(LineItem, 'Order' => '0', LineItem, 'Order' => '1' ...)
Are these solutions typical and/or viable? What would commonly be seen in a production environment?
As per the advice given by Matt S above, this is the implementation I will go with.
private function lineItemsFromInvoice($xeroInvoice) : array
{
$lineItems = array();
$index = 0;
foreach($xeroInvoice[XeroKeys::_XERO_INVOICE_KEY_LINE_ITEMS] as $value) {
$value["index"] = $index;
array_push($lineItems, $value);
$index++;
}
return $lineItems;
}
The question is now can I guarantee a php array() will add the ["index"] keys at the end?
I just need to update multiple rows at time.
Am able to insert multiple rows at a time, like the code below,
foreach ($request->something as $key => $value) {
$data=array(
'db_table_field0'=> $request->form_something[$key],
'db_table_field1'=>$request->form_something2[$key],
'db_table_field2'=>$request->form_something3[$key],
'db_table_field3'=>$request->form_something4[$key],
);
tableModel::insert($data);
}
data is inserting, I tried same for update like,
foreach ($request->something as $key => $value) {
$auc_det_id = tableModel::where('value', $request->value[$key])->get();
$data=array(
'db_table_field0'=> $request->form_something[$key],
'db_table_field1'=>$request->form_something2[$key],
'db_table_field2'=>$request->form_something3[$key],
'db_table_field3'=>$request->form_something4[$key],
);
$auc_det_id->update($data);
}
It's not updating, some error like method update not found. I also tried save() instead of update() .
I checked if null $auc_det_id then data is not saving(no error)
You can try:
$data=array(
'db_table_field0'=> $request->form_something[$key],
'db_table_field1'=>$request->form_something2[$key],
'db_table_field2'=>$request->form_something3[$key],
'db_table_field3'=>$request->form_something4[$key],
);
tableModel::where('value', $request->value[$key])->update($data);
I'm using codeigniter.
I'm trying to compare some posted values from a form with entries from a database.
Put simply, i want to check to see if the entry is already in the database, if so ignore the posted data, but if there is no database entry then add to the database.
My thinking was that it shouldn't actually be that hard, but having some issues, and now im completely confused. Any pointers in the right direction would be appreciated.
I have an array coming from POST $assigned_ids
And i want to compare that with the data from $assign_data which is being output from the database.
I've been trying foreach loops, looping over the posted data, and then inside that looping through the database and comparing and adding if neccessary.
It works upto a point, but if there is data coming from the database, its adding multiple entires.
Heres my code, surely im over complicating things?
// posted values foreach - loop through all posted values
foreach($assigned_ids as $id) {
if(is_array($assign_data) && count($assign_data) > 0) {
// query all data in assignments table
foreach($assign_data as $key => $value) {
// is the user id from assignments table in posted id's
if(in_array($value->user_id, $id)){
// if it is, then do the course id's match as well? if so, do nothing, already an entry
if($value->course_id == $course_id) {
echo "match id and course, do nothing";
} else {
// else if there isnt an entry for this user for this course, add the entry
$add_data = array(
'user_id' => $value->user_id,
'course_id' => $course_id,
'org_id' => $org_id
);
$this->assignment_model->save_org_assignments($add_data);
}
} else {
// the user id was not in the array from the db, but was in the posted vars, so log in db
$add_data = array(
'user_id' => $id,
'course_id' => $course_id,
'org_id' => $org_id
);
$this->assignment_model->save_org_assignments($add_data);
}
}
} else {
$add_data = array(
'user_id' => $id,
'course_id' => $course_id,
'org_id' => $org_id
);
$this->assignment_model->save_org_assignments($add_data);
}
}
I think your main issue is your array is not properly structured that's why your having a hard time.
My opinion is to predefined your db result after fetching it.
function getAssignedData(){
// its better to get the only field you'll need than to fetch everything
$result = $this->db->select($field)->get();
if($result->num_rows()){
$existing_ids = [];
foreach($result->result() as $row){
$existing_ids[] = $row->$field;
}
return array_flip($existing_ids);
}
return FALSE;
}
And you can already compare the values like this
foreach($assigned_ids as $id)
{
if(!isset($existing_ids[$id])) {
// do something
}
}
Hope that helps.
Attached code taken from cakephp bakery, where someone uploaded a sample about custom validation rules.
class Contact extends AppModel
{
var $name = 'Contact';
var $validate = array(
'email' => array(
'identicalFieldValues' => array(
'rule' => array('identicalFieldValues', 'confirm_email' ),
'message' => 'Please re-enter your password twice so that the values match'
)
)
);
function identicalFieldValues( $field=array(), $compare_field=null )
{
foreach( $field as $key => $value ){
$v1 = $value;
$v2 = $this->data[$this->name][ $compare_field ];
if($v1 !== $v2) {
return FALSE;
} else {
continue;
}
}
return TRUE;
}
}
In the code, the guy used a foreach to access an array member which he had its name already!
As far as I understand - it's a waste of resources and a bad(even strange) practice.
One more thing about the code:
I don't understand the usage of the continue there. it's a single field array, isn't it? the comparison should happen once and the loop will be over.
Please enlighten me.
In the code, the guy used a foreach to access an array member which he had its name already! As far as I understand - it's a waste of resources and a bad(even strange) practice.
The first parameter is always an array on one key and its value, the second parameter comes from the call to that function, in a block named as the key... So, all you need is to send the key and no need to iterate
The code uses foreach to iterate through $field, which is an array of one key value pair. It all starts when the validation routine invokes identicalFieldValues, passing it two values - $field, which would be an array that looks like:
array (
[email] => 'user entered value 1'
)
The second parameter $compare_field would be set to the string confirm_email.
In this particular case, it doesn't look like it makes a lot of sense to use foreach since your array only has one key-value pair. But you must write code this way because CakePHP will pass an array to the method.
I believe the reason why CakePHP does this is because an array is the only way to pass both the field name and its value. While in this case the field name (email) is irrelevant, you might need in other cases.
What you are seeing here is one of the caveats of using frameworks. Most of the time, they simplify your code. But sometimes you have to write code that you wouldn't write normally just so the framework is happy.
One more thing about the code: I don't understand the usage of the continue there. it's a single field array, isn't it? the comparison should happen once and the loop will be over. Please enlighten me.
Indeed. And since there are no statements in the foreach loop following continue, the whole else block could also be omitted.
A simplified version of this would be:
function identicalFieldValues($field=array(), $compare_field=null)
{
foreach ($field as $field) {
$compare = $this->data[$this->name][$compare_field];
if ($field !== $compare) {
return FALSE;
}
}
return TRUE;
}
And I agree with you, the loop only goes through one iteration when validating the email field. regardless of the field. You still need the foreach because you are getting an array though.