Insert in Foreach PHP - php

I have PHP:
if($post['for']){
foreach($post['for'] as $value){
$saveMsgObjFor->message_id = $save;
$saveMsgObjFor->object_type_id = 4;
$saveMsgObjFor->object_ref_id = $value;
$saveMsgObjFor->object_email = null;
$saveMsgObjFor->save($update);
}
}
But it just save first loop. For twice, it show error:
Statement could not be executed (23000 - 1062 - Duplicate entry
'33' for key 'PRIMARY'
33 is field message_object_id and it was auto increment. Help me, please..

Based on the hint in this answer, it would appear that you need to explicitly set the message_object_id to null. First time round it defaults to null, but then after the save() it gets set to the auto increment value, so you need to explicitly reset it, for example:
foreach($post['for'] as $value){
$saveMsgObjFor->message_object_id = null;
$saveMsgObjFor->message_id = $save;

I presume you should remove the following line from your code:
$saveMsgObjFor->message_id = $save;
I'm not overly familiar with the Zend framework but it looks like you're trying to assign the same value to a auto_increment, which won't work, as it's the row's identifier and must be unique. Hope this helps!

Related

Array_push doesn't make new key, instead replaces current value

I'm kinda lost here.
So here is what i'm trying to do.
I have a session, that's called "test", i have set the session to be an array every time that $_POST['process'] isset.
The $_POST['process'] is containing a integer, that's fetched from a DB Table.
Here's my code:
if(isset($_POST['process']))
{
$_SESSION['test'] = array();
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
It work's at first time, here's the result:
[test] => Array
(
[0] => 21311
)
I was expecting, that it would create a new key, and assign it to the other value that get's fetched from $_POST['process'] - but instead it just overwrites the 0 key.
What am i doing wrong here?
Kind regards
In your code you're writing $_SESSION['test'] = array(); which is resetting the value of $_SESSION['test'] to an empty array. Therefore it has removed your previous value and have put in your new one.
To fix this check if $_SESSION['test'] is already set, if it's not do $_SESSION['test'] = array();, otherwise just insert new values.
Full example:
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
}
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
Honestly, this is one precise case where using array_push() is a disadvantage versus its alternative square bracket syntax.
array_push() requires you to declare the empty array in advance; [] will not AND it is functionless AND it is more brief to code.
Furthermore, I am nearly 100% sure that you don't actually want to know the new element count after pushing. The PHP Manual says:
Returns the new number of elements in the array.
...so, if you do want to know the new count, then perhaps rename your variable from $array_merge to $array_size or $array_count or $array_length.
I know I wouldn't want to write an extra condition just to declare an empty variable then use a function to add a new element, especially when it can be done in one line
if(isset($_POST['process'])) {
$_SESSION['test'][] = $_POST['process']; // all done
}
This will work the first time and every time as desired.

PHP - Get the previous value of a session?

Basically I have a session value that will get updated periodically, but I need to save the previous value of the session.
Here is what I have got so far:
$value = $_GET['value'];
$_SESSION["prev-value"] = $_SESSION["value"];
$_SESSION["value"] = $value;
And the problem of course is that when I go to do <?php echo $_SESSION["prev-value"]; ?> it will be overwritten by the new value as we are checking if it is equal to the new value.
I don't want to have to store previous values in a database or text file, would that be the only way or is there any way to get past that?
Side Note:
I only need the last value, so I don't need to keep a massive lot, just the value before the newest
Do it only when you are having the GET parameter to set it. Technically you should be using POST to update or change values in the server side, which includes sessions.
if (isset($_GET['value'])) {
$value = $_GET['value'];
$_SESSION["prev-value"] = $_SESSION["value"];
$_SESSION["value"] = $value;
}
With the above way, unless you have /?value=something, your session value will not be affected.
Update: With your comments, it looks like it's worth trying out having previous values as an array. So slightly change your $_SESSION["prev-value"] as an array.
if (isset($_GET['value'])) {
$value = $_GET['value'];
if (!isset($_SESSION["prev-value"]))
$_SESSION["prev-value"] = array();
$_SESSION["prev-value"][] = $_SESSION["value"];
$_SESSION["value"] = $value;
}
This way, you would have a history of previous values that are iterable and you don't need a Database or a Text File. :) Even if the same values get set too many times, you can use the PHP function array_unique() to get the unique values of array and if you are crazy, array_reverse() it and get the second [1] value for the previous one. ;)
To get the previous one, what you might need to do is this:
$lastValue = array_reverse(array_unique($_SESSION["prev-value"]));
if (count($lastValue) > 1)
$lastValue = $lastValue[1];
echo $lastValue;
Set previous value as blank first time. and change your code as
$_SESSION["prev-value"] = $_SESSION["value"] ?? '';
$_SESSION["value"] = $_GET['value'];
Flow of code
$_SESSION["prev-value"]---------------$_SESSION["value"]
""---------------10 ----->First time load
10---------------20 ----->Next time load
20---------------30 ----->Next time load
......
......

Transform any null input to empty string

So I've got a while loop, inside I have $array_collections that gives me 35 value per loop, I want to verify for every value if it's equal to NULL then give it an empty string. I did that :
while ($array_collections = tep_db_fetch_array($query)) {
foreach ($array_collections as $key => $value) {
if (is_null($value)) {
$array_collections[$key] = "";
}
}
$docs[] = new \Elastica\Document('', \Glam\HttpUtils::jsonEncode(
array(
'X' => $array_collections['X'],
... etc
)));
}
This technically should work, but the loop goes over 500K elements so it's huge, and for every element we put it into a table, problem is that I run out of memory at some point. So is there another simple way to give any given NULL value an empty string without looping?
well, you can put NOT NULL constraint with empty string as DEFAULT value in the DB for that so you dont need to do that in php using looping, but if you dont want to change the DB design then you can use COALESCE in your query
select COALESCE(yourfield,'') from table
it will convert NULL value into empty string
You can use array_map function to replace null values into empty string.
$array_collections=array_map(function($ar)
{
if(isset($ar) && $ar!=null){
return $ar;
}
return '';
},$array_collections);
Above code replace all null values to empty string. No need of loop.
you can use array_walk:
function replace_null(&$lsValue, $key) {
if(is_null($lsValue)) {
$lsValue = "";
}
}
array_walk($array_collections, 'replace_null');

PHP compare subsequent array element to previous

So i'm having trouble getting a bit of code to work. Essentially what I want to do is:
in a foreach loop, if a given array value is set, compare that existing value to the current loop value, then set the existing value = current value (for the iteration) if the existing value is already greater than current val. Here is the code i'm working with:
if ($usedebayxml->ack == 'Success') {
foreach($usedebayxml->searchResult->item as $key => $value) {
if(isset($newarray[1]['TotalCost'])) {
if($newarray[1]['TotalCost'] > ((integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice)) {
$newarray[1]['Title'] = (string)$value->title ;
$newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
$newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
$newarray[1]['Condition'] = 'New';
$newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
}
}
else
$newarray[1]['Title'] = (string)$value->title;
$newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
$newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
$newarray[1]['Condition'] = 'Used';
$newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
}
}
With this code, what is returned is ultimately the values in the LAST key object in the xml file (im using simpleXML if that helps). In other words, i don't think the first if block (if isset) is being entered into, and the values are being set to whatever the values are for the current iteration. Can anyone see any flaw in my logic here? I've been stumped on this one for a while.
I am a supreme idiot. The logic here is fine, i was just missing a { for the opening else block. dur! After adding this, this bit of code works as intended :)
I'm surprised though that i wasn't throwing any errors without having this....I think that was probably throwing me off in determining why it wasn't working originally.

CakePHP: How to switch two row values from a unique field?

I need to change the value of two rows in the order field of my database. This field is unique.
What I tried:
Storing the value of both items in a PHP variable,
Setting the first row's field value to NULL (nulls are accepted in the field),
Setting the value of the second row's field to the value that was held on the first row,
Setting the first row's field value to the original second row field value.
It doesn't work, since I am getting a "dupplicate entry" error when executing the order change. I can't seem to find out how to do this using CakePHP.
Here is the code that I have written (even though it's not functionnal):
if ($second_row) {
$next = $second_row['Immeuble']['order'];
$prev = $first_row['Immeuble']['order'];
$this->Immeuble->id = $first_row_id;
$this->Immeuble->saveField('order', 'null');
$this->Immeuble->id = $second_row['Immeuble']['id'];
$this->Immeuble->saveField('order', $prev);
$this->Immeuble->id = $first_row_id;
$this->Immeuble->saveField('order',$next);
}
of course its dublicate key
you defined id two times
$this->Immeuble->id = $first_row_id;
and
$this->Immeuble->id = $second_row['Immeuble']['id'];
and then
$this->Immeuble->id = $first_row_id;
try remove this last line
The code I stated above is fully functionnal. I just had inverted some values, which would screw everything up. I will not delete the question in case someone else needs to do something similar.

Categories