query with IF not working - php

Hi I have some variables which are calculated with API's in an early script but successfully return the value $TotalDistance (based on postcode to postcode driving distances).
I have added a checkbox to tick when it is a return journey, the idea is that it then doubles the distance, this is my query.
if($values['Return']>0) $TotalDistance=2*$TotalDistance; else $TotalDistance=$TotalDistance;
However the result is still returning as a single (x1) value even if checkbox is ticket? Why

I'm assuming this is a HTML form and $values is either a reference to, or built from $_POST.
When submitting a checkbox in an HTML form, there are two possible outcomes:
Unchecked - doesn't get submitted and won't be part of the array
Checked - the VALUE of the checkbox gets submitted
Example:
<input type="checkbox" name="Result" value="MyResultValue" />
<input type="hidden" name="HidValue" value="OtherValue" />
Would yield this when unchecked:
array (size=1)
'HidValue' => string 'OtherValue' (length=10)
And when checked:
array (size=2)
'Result' => string 'MyResultValue' (length=13)
'HidValue' => string 'OtherValue' (length=10)
So, to check if it is checked (I like to include a validation check to make sure the value wasn't changed) do something like this:
$values = $_POST; //again I'm assuming something like this is happening
if( isset($values['Result']) && $values['Result'] == 'MyResultValue' )
If you don't care about the validation - just use the isset.

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'];?>

Multiple checkbox values in array gives strange characters in database

I'm saving the values from a checkbox in an array to the database, but in the database the field contains strange characters like: s:44:"a:2:{i:0;s:8:"0-4 years";i:1;s:8:"10th group";}";
I only need the parts 0-4 years and 10th group. How can I prevent the characters get it the way I want?
This is part of the form:
<input type="checkbox" name="wmw_age[]" value="0-4 years">
<input type="checkbox" name="wmw_age[]" value="10th group">
This is the way I get it to the database after submit:
$data=serialize($_POST['wmw_age']);
update_post_meta($post_id, 'wmw_age', $data);
If both fields are checked, this is the result in the database:
s:44:"a:2:{i:0;s:8:"0-4 years";i:1;s:8:"10th group";}";
Is it possible to only get this in the database: 0-4 years, 10th group
I hope someone can help me with this!
Thanks.
This should do the trick:
$data = join(', ', $_POST['wmw_age']);
You do not have to serialize the array, it can be concatenated with the join function, which will turn it into a string by joining all values with a given string(glue). ( ', ' in the above example )
The result will be: 0-4 years, 10th group in case both checkboxes are checked, 10th group or 0-4 years in case only one checkbox is checked and an empty string in case none is checked.
Thanks to #RiggsFolly for pointing out, that the serialized string is serialized again by update_post_meta, so a deserialization is unnecessary.

JSON encode_decode weird behave PHP

I have array input in HTML Form as below
<select name="age[]" id="ageFrom">..Age Options..</select>
<select name="age[]" id="ageTo">..Age Options..</select>
Upon submission, I am saving data in mysql database as json_encoded value like ["20","25"]
foreach($request->request as $key => $value) {
ProfileSettings::create([
'uid' => $curMID,
'code' => 'preference',
'key' => $key,
'value' => json_encode($value),
'serialized' => 1
]);
});
Now, when it get this value from DB and try to decode it as
$val = json_decode(["20", "25"]) OR json_decode(["20", "25"], true)
My DB returns value like
Then i get an error like
htmlspecialchars() expects parameter 1 to be string, array given
Kindly help me to get 20 and 25 as $val[0] and $val[1]
Thing is, you're calling json_decode on a php array [ ].
It expects a string, which it'll convert to an array.
Perhaps you wanted to use json_encode instead? If so, change your code to:
$val = json_encode(["20", "25"]) OR json_encode(["20", "25"], true)
The problem is that the value coming from the data base is ["20", "25"] and when is inserted in the json_decode() function is interpreted as an array.
To solve the problem insert the value in between double quotes.
$val = json_decode("$result") or $val = json_decode('["20", "25"]')

PHP _GET values in an array

I have list of items, after selecting them and pressing a submit button
there's kind of a query in the url bar as such :
adrese-id=7&food-id=1&food-id=2&food-id=3&food-id=4
Trying to get all of the food IDs in an array but no luck so far, tried doing:
$ids = $_GET['food-id'];
but that just has the last value, which is 4...
How do I get those values in an array?
You have to name your field to indicate it's an "array". So, instead of food-id, append brackets to the end to make it food-id[]
For example:
<input type="checkbox" name="food-id[]" value="1"> Pizza
<input type="checkbox" name="food-id[]" value="2"> Cheese
<input type="checkbox" name="food-id[]" value="3"> Pepperonis
Accessing it in PHP will be the same, $_GET['food-id'] (but it will be an array this time).
In php the $_GET array has $key => $value pairs. The 'food-id' in this case is the $key.
Because all your values (1,2,3,4) have the same key: 'food-id' the array looks like this:
$_GET = [
'food-id' => 1,
'food-id' => 2,
'food-id' => 3,
'food-id' => 4,
]
This will always be parsed with the last $key => $value pair being used:
$_GET = [
'food-id' => 4
]
The solution to this is always using unique keys in your arrays.
You really need to provide the HTML fragment that generates the values. However if you look at your GET request the values for food-id are not being submitted as an array which is presumably what you want. Your GET request should look more like:
adrese-id=7&food-id[]=1&food-id[]=2&food-id[]=3&food-id[]=4
which should give you a clue as to how your HTML form values should be named.

Random number of FORM fields being prepared for database

I've found myself with the following problem: I have form with a random number of fields. (This is so users can enter their fellow team members's names -- and there's no set size for teams.) I need this inputted data to be formatted in preparation for being stored in a database.
The database structure is fine, it's just getting a random number of $_POSTs and putting them into an array that's the issue.
So far I've got some javascript that allows the user to create/remove an infinite number of fields, with incrementing ids/names (e.g. TeamMemberName1, TeamMemberEmail1, TeamMemberName2, TeamMemberEmail2, etc.).
Right now I've created an ugly series of PHP statements that puts a reasonable amount of POSTed data into a multidimenional array -- I don't see why a team should ever be bigger than 50 -- and then I was going to process the array to remove any blank rows before passing it onto the database.
Example:
$submittedTeamMembers =
array ( "teamMember1" =>
array ( "name" => $_POST["teamMemberName1"],
"email" => $_POST["teamMemberEmail1"])
);
But I'm guessing there's a better way!
Your input names can be in array form, which PHP will understand perfectly. Example:
<input type="text" name="teamMembers[0]['name']" />
<input type="text" name="teamMembers[0]['email']" />
which PHP will interpret after post as you'd expect:
//print_r($_POST['teamMembers']);
Array
(
[0] => Array
(
[name] => foo
[email] => bar
)
)
Just give all your fields a name of 'TeamMemberName[]' or 'TeamMemberEmail[]'. Each should be posted regardless of whether or not the value is there, so they should always match up.
This will pass them as an array to your server-side PHP script, so you can access them like so:
$teamMemberNames = $_POST["teamMemberName"];
$teamMemberEmails = $_POST["teamMemberEmail"];
for ($i = 0; $i < count($teamMemberNames); $i++)
echo "name = {$teamMemberNames[$i]}, email = {$teamMemberEmails[$i]}\n";

Categories