Undefined offset when removing input field that is not the last one - php

I am using this HTML and JQuery code to add input fields:
https://www.sanwebe.com/2013/03/addremove-input-fields-dynamically-with-jquery
with a few changes, my code resembles this, shortened:
$(wrapper).append('<?php echo $this->Form->input("ticket.' +index+ '.startdate"); ?>');
where index is a var that I'm incrementing and decrementing when the add field or remove field buttons are being selected.
The problem is when I remove an element that is not the last one, for example:
I remove text 1, 2, or 3 and then submit it, I get the Undefined offset error, naturally, since the index var of the created elements stays the same, and the server gets
ticket.0.startdate
ticket.2.startdate
ticket.3.startdate
and has no idea where the ticket.1.startdate is.
PHP code:
$festivalticket = $this->Festivaltickets->newEntity();
if ($this->request->is('post')) {
$festivalticket = $this->Festivaltickets->patchEntity($festivalticket, $this->request->data, [
'associated' => [
'Tickets'
]
]);
}
I want to know if there's a way to get past this.
Thank you.

Us an array for your form fields. ticket_startdate[] will dynamically append array elements, so something like:
$(wrapper).append('<?php echo $this->Form->input("ticket_startdate[]"); ?>');
Then just loop through without worrying about the index:
foreach($_POST['ticket_startdate'] as $key => $start_date) {
echo "index $key is $start_date";
}
I can't tell what's going on with the PHP you posted. It looks like a framework so it may handle the array correctly.

Related

How to use php rand fucuction to generate 2 sets of data that match

i need to know how i can have a array with the rand function show up lets say a email and a password in two different text areas how would i do this
this is what ive already tried but keeps giving me string number instead of detail
index.php:
include "details.php";
$gen=array_rand($test);
$stock=count($test);
<form method='post' action='free.php'>
<b>Email:</b><textarea name="email"><?php echo "$gen";?></textarea><br>
<b>Password:</b><textarea name="password"><?php echo "$gen";?></textarea>
<center>
<button type="submit">Generate</button><br>
stock:<?php echo "$stock";?>
</center>
</form>
details.php
$test = [
['account' => 'acc1','pass' => 'pass1'],
['account' => 'acc2', 'pass' => 'pass2']
];
project link:
http://noxxeraltgen.tk/minecraft/free.php
array_rand() returns an index and not the actual array element. From the manual...
Return Values
When picking only one entry, array_rand() returns the
key for a random entry. Otherwise, an array of keys for the random
entries is returned. This is done so that random keys can be picked
from the array as well as random values. Trying to pick more elements
than there are in the array will result in an E_WARNING level error,
and NULL will be returned.
You also need to specify the part of the array you want to output for each item, so...
echo "$gen";
Should be either
<?php echo $test[$gen]['account'];?>
or
<?php echo $test[$gen]['pass'];?>

jquery ajax sortable pass data in object as key value after serialize

I am using jquery ui sortable to reorder a list via php, I get the ids like so:
var ids = $('#sort1').sortable('serialize');
It works fine when on update in the ajax call I pass the data in the ajax call like so:
data: ids
And then catch in inside my php script like so (notice singular id):
$getids = $_POST['id'];
All that works fine, however I want to pass the data inside an object because there are other things I want to pass along as well, but it does not seem to be working.
I tried:
data: {
id: ids
},
then I get this php error:
Warning: Invalid argument supplied for foreach() in C:\wamp\www\sortable\sort.php on line 8
And I also tried changing $getids = $_POST['id']; to $getids = $_POST['ids']; but then I get unidentifed index and also invalid argument error.
How can I pass the ids inside an object as key value pair?
EDIT:
the foreach code
$count = 1;
foreach ($getids as $key => $id) {
$q = "UPDATE titles SET sorting='$count', parent_id='1' WHERE id='$id'";
$r = mysqli_query($dbc, $q);
if ($r) {
echo 'done <br>';
} else {
echo 'problem <br>' . mysqli_error($dbc);
}
$count++;
}
I had this issue and came across this post, as it doesn't include any code to solve the issue. I finally found a solution that worked for me...
In my Ajax request I converted my sortable UI to an array using the following:
var data = $(this).sortable('toArray');
Then the Ajax request was sent the following way:
data: { sectiononelink: data, currentUserID: user_id },
Then because the sortable to array function gave me a string such as sectionone-asectionone-bsectionone-csectionone-d etc... I only wanted the letters after the "sectionone-" part of the string as I was looking to order a list in my html using the letters a - z.
In my PHP I used a foreach loop which contained:
$profileLinkOrder = "";
foreach($_POST['sectiononelink'] as $value)
{
$profileLinkOrder .= substr(strstr($value, "-"), 1);
}
Then the variable $profileLinkOrder would come out like abcdefg etc... Depending on how I had my sortable UI list on my HTML page.
This worked for me so I hope someone else can use this to solve this problem. I could not find any other solutions on the web. Let me know if this helps.

Create key => value pair array only if variables are set

I have a number of items of data. Sometimes the var is not created/set, sometimes it is. This is because the var data comes from a form with optional fields.
I have created the variables only if the information is present as such:
if(!empty($_POST["user-jobtitle"])){
$idealJobTitle = $_POST["user-jobtitle"]; }
So if the field user-jobtitle is not filled in, then $idealJobTitle is not created.
I now wish to create an array with a key for each value. But I only want to add to the array if that variable exists. Otherwise, I just want to omit it.
I have written code below which I know is wrong but follows the sort of logic I am after. What is the correct way to do this? Do I really have to run through nested if statements checking if the var exists and only then pushing to the array?
$other_info = array (
"other_info" => array(
if(isset($message)){
"message" => $message
},
if(isset($salaryRange)){
"salary_range" => $salaryRange
},
if(isset($idealJobTitle)){
"ideal_job_title" => $idealJobTitle
}
if(isset($applyFor)){
"ideal_applying_for" => $applyFor
}
)
);
An expected result, if the user has not provided an ideal job title on the form, would be as such:
array(1) {
["other_info"]=>
array(3) {
["message"]=>
string(18) "my message here"
["salary_range"]=>
string(19) "£25k - £30k"
["ideal_applying_for"]=>
string(18) "Cat cuddler"
}
}
As you can see in the above, the ideal_job_title key and value are simply not present.
You should not conditionally declare variables. That's just asking for problems later on.
Unpacking values from one array into a variable and then conditionally packing them back into an array is needlessly complex. Keep your data in an array and move it around in one "package".
You can't have nested if statements within an array declaration.
The most useful way to handle this would be to use names in your form that you're also going to use later on in your $other_info array. Translating between various variable and key names throughout your code is just terribly confusing, pointless and needlessly requires a ton of additional code. In other words, why does the same piece of information need to be called user-jobtitle and $idealJobTitle and ideal_job_title in different contexts? If you'd keep it consistent, you could simply filter empty values and be done with it:
$other_info = array('other_info' => array_filter($_POST));
Yup, array_filter gets rid of empty elements without individual if statements. You can further use array_intersect_key and similar functions to further filter out keys.
If you name variables as key in the array, you can use compact function. Undefined variable will not be in array
$ar = compact("message", "salaryRange", "idealJobTitle", "applyFor");
You can use the below code :
$other_info = array();
if(isset($message)){
$other_info['other_info']["message"] = $message;
}
if(isset($salaryRange)){
$other_info['other_info']["salary_range"] = $salaryRange;
}
if(isset($idealJobTitle)){
$other_info['other_info']["ideal_job_title"] = $idealJobTitle;
}
if(isset($applyFor)){
$other_info['other_info']["ideal_applying_for"] = $applyFor;
}
You already have a code that works and puts the values in variables. Create an empty array and put the data directly in the array under various keys instead of individual variables:
$info = array();
// Analyze the input, put the values in $info at the correct keys
if (! empty($_POST["message"])) {
$info["message"] = $_POST["message"];
};
if (! empty($_POST["salaryRange"])) {
$info["salary_range"] = $_POST["salaryRange"];
};
if (! empty($_POST["idealJobTitle"])) {
$info["ideal_job_title"] = $_POST["idealJobTitle"];
}
if (! empty($_POST["applyFor"])) {
$info["ideal_applying_for"] = $_POST["applyFor"];
}
// Voila! Your data is now in $info instead of several variables
// If you want to get the structure you described in the non-working code you can do:
$other_info = array(
"other_info" => $info,
);

Iterate over KEYLESS JSON array?

I'm building a shopping cart and using a cookie to store the cart contents in a JSON object.
On each page, using Javascript, I need to retrieve the cookie, parse the JSON and iterate over each row, to display the described product in the basket summary.
I decided not to use keys in the array, since if I have a record of the designation of each position, why do I need to store it in the cookie. I thought that was a smart idea, but now all my searching turns up are suggestions to use the keys.
This is a sample of the JSON:
{
"9999.9999":["CentOS6",2,"0.5",150,"23.90"],
"0002.0004":["Support5","","3",5,"12.99"],
"9999.9999":["UbuntuServer12.04LTS",1,"1",220,"42.60"]
}
I was expecting to be able to access the 'price' for example (which is in the last field of each row) of the 2nd record, like so:
basket = JSON.parse(basket);
price = basket[1][4];
That doesn't seem to work.
There are really two parts to this question.
How to cherry pick a value directly from the basket?
How to iterate through it, allowing me to operate on each row in turn?
In case you're wondering about the first field. That is the SKU of the product. The reason there are two "9999.9999" is because that is a reserved number, indicating that the product was a 'custom' product (doesn't refer directly to a catalogue item).
UPDATE
Based on #Samer's answer below, I have updated the code to use arrays, as follows:
The JSON now looks like this:
[
["9999.9999","CentOS6",2,"0.5",150,"23.90"],
["0002.0004","Support5","","3",5,"12.99"],
["9999.9999","UbuntuServer12.04LTS",1,"1",220,"42.60"]
]
I'm now attempting to access it from the cookie as follows:
var basket = readCookie('basket');
basket = JSON.parse(basket);
alert( 'Price of item 2 =' + basket[1][5] );
Only, instead of alerting, 'Price of item 2 = 12.99' I get 'Price of item 2 = undefined'.
I'm wondering what I've done wrong?
UPDATE 2
Still having trouble with this. Maybe I should explain how we're getting the data into the cookie.
The array on the cookie can be updated on the server using PHP (when adding custom items) or client-side using Javascript when a catalogue item is added.
Currently, I'm concentrating on items added server side. I'm using the following code to add the cookie:
<?
extract($_POST, EXTR_SKIP);
// Get contents of existing basket (if any) minus last ']'
// so that it's ready to be added to.
if (isset($_COOKIE['basket'])) {
$basket = json_decode($_COOKIE['basket']);
$chars = strlen($basket)-1;
//echo "<pre>".var_dump($basket)."</pre>";
$cookieVal = substr($basket, 0, $chars);
$cookieVal .= ",
[\"9999.9999\",\"$sltOS\",$vcpuPoints,\"".$ramPoints."\",$storagePoints,\"".$baseServerCostMonthUSD."\"]]";
$cookieVal = json_encode($cookieVal);
/*
* Sample format
*
[["9999.9999","CentOS6",2,"0.5",150,"23.90"],
["0002.0004","Support5","","3",5,"12.99"],
["9999.9999","UbuntuServer12.04LTS",1,"1",220,"42.60"]]
*
*/
} else {
$cookieVal = json_encode("[[\"9999.9999\",\"$sltOS\",$vcpuPoints,\"".$ramPoints."\",$storagePoints,\"".$baseServerCostMonthUSD."\"]]");
}
$exp = time()+3600; // sets expiry to 1 hour;
setcookie ( 'basket' , $cookieVal, $exp, '/' );
Then client-side for reading the cookie, I have this, which is called when the page is loaded:
function initBasket() {
var basket = readCookie('basket');
if (isJSON(basket)) {
// We'll populate the basket
basket = JSON.parse(basket);
alert(basket[1][5]);
} else {
$('#sList').html('Your basket is empty.');
return;
}
}
UPDATE 3
Finally got it working. Thanks for your help.
Maybe the code can help others, so I've included the final code below:
The PHP:
if (isset($_COOKIE['basket'])) {
$cookieVal = json_decode($_COOKIE['basket']);
$cookieVal[] = array
(
"9999.9999",
$sltOS,
$vcpuPoints,
$ramPoints,
$storagePoints,
$baseServerCostMonthUSD
);
$cookieVal = json_encode($cookieVal);
} else {
$cookieArr[] = array
(
"9999.9999",
$sltOS,
$vcpuPoints,
$ramPoints,
$storagePoints,
$baseServerCostMonthUSD
);
$cookieVal = json_encode($cookieArr);
}
// Save VPS choice in basket cookie
$exp = time()+3600; // sets expiry to 1 hour;
setcookie ( 'basket' , $cookieVal, $exp, '/' );
The Javascript:
function initBasket() {
var basket = readCookie('basket');
if (isJSON(basket)) {
// We'll populate the basket
basket = JSON.parse(basket);
alert(basket[1][5]);
} else {
$('#sList').html('Your basket is empty.');
return;
}
}
If the JSON has no keys then it's an array, simply build your data using an array instead of key/value pairs.
var data = [
['CentOS', ''],
['Another Product', ...],
];
UPDATE:
So now based on your new answer, it looks like you're trying to JSON.parse the actual array. JSON.parse usually takes in a string value which has the array and then parses it into an actual array.
To see what I mean take your data array and run it through JSON.stringify and you will see the output, that same output you can then run it through JSON.parse
The problem is in PHP: You json_encode your array twice.
Here you manually encoded it once:
$cookieVal .= ",
[\"9999.9999\",\"$sltOS\",$vcpuPoints,\"".$ramPoints."\",$storagePoints,\"".$baseServerCostMonthUSD."\"]]";
Then here, you do it again:
$cookieVal = json_encode($cookieVal);
So as a result you get a string when you parse json it in javascript.
Obviously, second basket[1][4] gives you an undefined value, since basket is a string and basket[1] is a character.
It helps to use firebug or other debugging utility to take a look what data you get at every step.
So. Simply build an array of arrays in PHP and then json_encode it (once) and your js should work.
{
"9999.9999":["CentOS6",2,"0.5",150,"23.90"],
"0002.0004":["Support5","","3",5,"12.99"],
"9999.9999":["UbuntuServer12.04LTS",1,"1",220,"42.60"]
}
Mind the curly-brackets. This indicates that this is an object.
You cannot iterate through an object by numeric index.
Also mind the duplicated key "9999.9999", the first row will be overwritten by the third row.
You may try to use a for-in loop for looping through an object but this is not recommended.
var basket = JSON.parse(basket);
for(var key in basket)
{
var price = basket[key][4];
// do something with the price.
}
Anyways, this JSON object has structural problem. You should consider a better structure, an plain-old array should be good enough.

How to dynamicly set a array variable?

I have a problem with this code:
$a['i'] = 1;
$b = '$a[\'i\']';
echo $$b;
It display an error:
Notice: Undefined variable: $a['i'] in test.php on line 6
Is it possible to create dynamic array variable?
Thanks for your time.
EDIT: In my example I am trying to edit an multidimensional array. There is a problem when I try to add data to my array (JSON). I don't have fixed dimension of array, it my be 2 or more dimension (I am building a model for Web form, and I want to add invalid value to JSON).
Now in one of the methods of Web form object I have code which checks repopulation object to add invalid value if needed.
I can not just add a value to JSON array, I need to edit it on multidimensional level.
For now I came up on solution to dynamically generate variable name and, then, edit it. If someone have solution it will be appreciated.
private $form = array(
'form_contact'=>array(
'attr'=>array('tag'=>'FORM', 'method'=>'post'),
'elem'=>array(
'fs_contact'=>array(
'attr'=>array('legend'=>'Kontakt', 'tag'=>'FSET'),
'elem'=>array(
'name'=>array(
'attr'=>array('SPAN'=>'Ime i prezime', 'title'=>'Unesite Vaše ime i prezime', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('req'=>'noscript', 'length'=>255),
'invalid'=>true), // Holds info that this is invalid
'www'=>array(
'attr'=>array('SPAN'=>'Web sajt', 'title'=>'Unesite Vaš sajt', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('length'=>255)),
'email'=>array(
'attr'=>array('SPAN'=>'E-mail', 'title'=>'Unesite Vaš email', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('req'=>'email', 'length'=>255)),
'message'=>array(
'attr'=>array('SPAN'=>'Poruka', 'cols'=>'60', 'rows'=>'5', 'title'=>'Unesite Vašu poruku', 'tag'=>'TEXTA', 'value'=>'nesto'),
'validat'=>array('req'=>'all')),
'submit_new_contact_form'=>array(
'attr'=>array('tag'=>'INPUT', 'type'=>'submit', 'value'=>'Pošalji poruku!'))
))// FS end
)) // Form end
);// Array end
You can't do it that way, as PHP thinks you're looking for a variable with the name $a['i'], rather than the 'i' key in the $a array.
The proper, and conventional, way is to use a dynamic key/index instead:
$b = 'i';
echo $a[$b];

Categories