I am trying to put some data into Amazon's simpledb. I need to enter multiple values for an attribute (comma separated), but as I have the script now it's entering all the values as one attribute. I think I need to create an array from the comma separated values in the textarea, but I don't know how to do that. Heck, I don't really know how to ask this question correctly. :)
Here's the code.
<?php require_once('./simpledb/config.inc.php'); ?>
<html>
<body>
<h1>Input Cities</h1>
<?php
$domain = "states";
if (!empty($_POST["state"])) { // if a value is passed from the key input field save it
$state = $_POST["state"];
} else {
$state = "";
}
$state = stripslashes($state); // remove PHP escaping
if (!empty($_POST["cities"])) { // if a value is passed from the key input field save it
$cities = $_POST["cities"];
} else {
$cities = "";
}
//$cities = stripslashes($cities); // remove PHP escaping
?>
<FORM ACTION="addcities.php" METHOD=post>
<label>State (Caps)</label><br>
<input type=text name="state" size=10 value="<?php echo $state; ?>"><br>
<label>Cities ('' & comma seperated)</label><br>
<textarea name="cities" cols=60><?php echo($cities); ?></textarea><br>
<INPUT TYPE=submit VALUE="Add Cities">
<?php
if (!class_exists('SimpleDB')) require_once('./simpledb/sdb.php');
$sdb = new SimpleDB(awsAccessKey, awsSecretKey); // create connection
$item_name = $state;
//$input_cities = array("value" => array($cities));
echo "<p>putAttributes() item $item_name<br>";
//$putAttributesRequest["make"] = array("value" => "Acura"); // Example add an attribute
$putAttributesRequest['City'] = array("value" => array("Blue","Red")); // Add multiple values
The previous line is the manual way of adding your multiple values into the attribute. I tried doing the following, which gets the value of the text area, but as I mentioned earlier it just creates one value that's comma seperated vs. multiple values.
$putAttributesRequest['City'] = $input_cities; // Add multiple values
The following is just the rest of the code.
$rest = $sdb->putAttributes($domain,$item_name,$putAttributesRequest);
if ($rest) {
echo("Item $item_name created");
echo("RequestId: ".$sdb->RequestId."<br>");
echo("BoxUsage: ".$sdb->BoxUsage." = " . SimpleDB::displayUsage($sdb->BoxUsage)<br>");
} else {
echo("Item $item_name FAILED<br>");
echo("ErrorCode: ".$sdb->ErrorCode."<p>");
}
?>
Use php explode function
For example:
$cities = explode(",", $_POST['cities']);
This will only work if your data is formatted like so:
New York,Las Vegas,Sydney,Melbourne,London
Change the first part of the explode function to match the formatting of your text area.
You can then do something like:
foreach ($cities as $key => $val){
echo trim($val) . '<br />';
}
Put your SimpleDB stuff inside the foreach loop above and use $val where you want to use the city name.
This will loop through the array and do the SimpleDB stuff on each city.
Explode the string on the commas.
$citiesArray = explode(",", $cities);
You'll then want to trim each of the cities to make sure there's not additional white space before or after the city name.
call_user_func_array("trim", $cities);
There is one more Request Parameters in PUT - Replace. Although its default value is false, please specify it as a false. If Replace is false the value will be added as a multi-value to that attribute and if it is true then it will replace the older value.
Also you need to add single pair of 'Attribute Name and Attribute value' each time in PUT request. i.e if you need multvalue V1 & V2 of Attribute A then in you request it would be like this -
https://sdb.amazonaws.com/
?Action=PutAttributes
&Attribute.1.Name=A
&Attribute.1.Value=V1
&Attribute.2.Name=A
&Attribute.2.Value=V2
&Attribute.3.Replace=false
&AWSAccessKeyId=[valid access key id]
&DomainName=MyDomain
&ItemName=Item123
&SignatureVersion=2
&SignatureMethod=HmacSHA256
&Timestamp=2010-01-25T15%3A03%3A05-07%3A00
&Version=2009-04-15
&Signature=[valid signature]
Related
I have the following Fiddle set up here Fiddle
As you can see, I am able to add inputs by clicking the Add Row button.
All inputs that are added have a unique id and name. The problem is, I cant just do something like
$actionInput = $_POST["actionInput"];
Because I might need
$actionInput1 = $_POST["actionInput1"];
$actionInput2 = $_POST["actionInput2"];
$actionInput3 = $_POST["actionInput3"];
Depending on how many rows are added. So how can I get all the inputs without knowing what inputs I need to grab?
Thanks
Actually, you need to maintain counter in hidden, which you will get at the time of posting the form in case you don't want to maintain elements as array, otherwise you can put elements as array as described below:
<input type=text name="inputs[]" />
Name your inputs with array boundary, like:
<input type=text name="actioninput[]" />
now you can itreate throught them in you POST or GET ( depends ) array:
print_r($_POST);
Assuming your JSFiddle works fine for you, following are the steps.
1) Get keys of $_POST.
2) Get maximum counter value from keys.
3) Take a for loop from 0 to count of post.
4) If counter is 0, no suffix, else, add counter as suffix.
5) Now, you get posted variable.
6) Repeat it for every element in rows.
<?php
$keys = array_keys($_POST);
$keys = implode(',', $keys);
$n = str_replace('actionInput', '', $keys);
$m = explode(',', $n);
$max = max($m);
for ($i=0 ; $i<=$max ; $i++) {
$suffix = ($i==0) ? '' : $i;
if (isset($_POST['actionInput' . $suffix])) {
echo "<br/>-".$_POST['actionInput' . $suffix];
}
}
replace name=actionInput with name=actionInput[]
it should be an array with same name
same thing will apply with all form fields generated dynamically whose values you'll need.
Change this line in Add row jquery event
return name + i to return name
Remove i from it and then
name=actionInput[]
print_r($_POST);
It will gives array of actioninput
Can I use php to read values from one input and store it in array?
I want to read multi integers from the user and calculate the total of them if the user entered ZERO!
For example, I add one input text and one submit:
<form method="GET">
enter numbers : <input type = "text" name="txt">
<input type = "submit" value = "Calculate">
</form>
then use php to read them !!
<?php
$n = #$_GET[txt];
$i=0;
while ($n!=0)
{
$ary[$i]=$n;
$i++;
}
if ($n==0)
echo #count($ary);
?>
it doesn't work .. what should I do here? There is the same problem in java, but there I can use scanner. Can any one help to solve it with php?
I think this is what you're asking for:
// Get the value of the input box, note that I put `txt` in quotes
// so I didn't need the `#`
$txt = $_GET ['txt'];
// `explode` will create an array from a string using the first
// parameter as a delimiter
$ary = explode (' ', $txt);
// Search the array for the ZERO value
if (array_search(0, $ary) !== false) {
// Output the sum of the array if the ZERO value is found
echo (array_sum ($ary));
}
A note: You should almost never use the # operator in PHP, if you do then you're likely doing some incorrect.
Not sure if the question title actually makes sense.
Anyway, what I'd like to do is be able to echo an individual value from a foreach loop.
Here's my code:
$headlines = array('primary_headline' => $_POST['primary_headline'], 'secondary_headline' => $_POST['secondary_headline'], 'primary_subline' => $_POST['primary_subline'], 'secondary_subtext' => $_POST['secondary_subtext']);
$city_name = "Dallas";
$ref_name = "Facebook";
$searches = array('$city_name', '$ref_name');
$replacements = array($city_name, $ref_name);
if(isset($headlines)) {
foreach($headlines as $headline) {
$headline = str_replace($searches, $replacements, $headline);
echo($headline['primary_headline']); // I thought this would do the trick
}
}
I thought that this would've echoed my city is Dallas when my city is $city_name was posted, unfortunately, this isn't the case and it merely echoes msps, which is the first letter of each input value:
<input name="primary_headline" type="text" value="my city is $city_name" />
<input name="secondary_headline" type="text" value="secondary headline" />
<input name="primary_subline" type="text" value="primary subline" />
<input name="secondary_subtext" type="text" value="secondary subline" />
<input type="submit" value="submit" />
If anyone could point me in the right direction, it would be very much appreciated!! :)
$searches = array('$city_name', '$ref_name');
The single quotes are making $searches literally contain the word $city_name, not the VALUE of $city_name. You don't need quotes while assigning variables:
$searches = array($city_name, $ref_name);
unless, of course, you're doing some kind of templating system and trying to do variable interpolation without eval().
Change
echo($headline['primary_headline']); // I thought this would do the trick
To
echo($headline) . PHP_EOL; // I thought this would do the trick
When you are using foreach you do not need to specify an index to the element, because foreach will handle iterating for you, so when you dereference something inside the loop, you are asking for a character from the string. Here you get the first character because 'primary_headline' is being interpreted as a 0.
$headlines = array('primary_headline' => $_POST['primary_headline'], 'secondary_headline' => $_POST['secondary_headline'], 'primary_subline' => $_POST['primary_subline'], 'secondary_subtext' => $_POST['secondary_subtext']);
This creates an array with key=>value pairs, not a multidimensional array. Looping through this array in a foreach loop will return only the values, i.e. $_POST['primary_headline'] for the first iteration, $_POST['secondary_headline'] for the second iteration, etc. This is why you're unable to access $headline['primary_headline'].
If you want to access "my city is Dallas" per your example, simply echo $headlines['primary_headline'].
If you want to echo each value:
foreach($headlines as $headline) {
echo $headline . PHP_EOL;
}
For good measure figured I should close this question with an answer (I've already placed it in the comments section as I couldn't add an answer).
The ampersand (&) must be used in order to assign a reference to the original array $headlines instead of copying it's valuables, thus updating it with any values created within the foreach() loop.
So, my code is now;
$headlines = array('primary_headline' => $_POST['primary_headline'], 'secondary_headline' => $_POST['secondary_headline'], 'primary_subline' => $_POST['primary_subline'], 'secondary_subtext' => $_POST['secondary_subtext']);
$city_name = "Dallas";
$ref_name = "Facebook";
$searches = array('$city_name', '$ref_name');
$replacements = array($city_name, $ref_name);
if(isset($headlines)) {
foreach($headlines as &$headline) {
$headline = str_replace($searches, $replacements, $headline);
}
echo ($headlines['primary_headline']) // This now has the value of $_POST['primary_headline'] along with the str_replace() function assigned to $headline
}
I'm basically looking to simply print out each of the allowed values in a CCK field..
i know the allowed values are stored inside a text field within the table: 'content_node_field'.
the values are then stored within 'global_settings'
I'm looking to somehow print out each individual allowed value using a PHP loop.
however with all values being stored within one text field.. im finding it hard to print out each value individually.
Something like this should do the trick.
// Get the global_settings like you described.
$serialized_data = db_result(db_query("..."));
// Unserialize the data.
$unserialized_data = unserialize($serialized_data)
// Foreach the allowed values.
$values = array();
foreach(explode("\n", $unserialized_data['allowed_values']) as $value) {
$values[] = $value;
}
If I am getting your question right, you can create PHP arrays by simply suffixing the [] to the names of the fields, so for example:
<input type="text" name="myname[]" />
Now you can get the values of the array like this:
foreach($myname as $value)
{
echo $value . '<br />';
}
Update Based On Comment:
You can use the json_decode function to convert your data to array and then manipulate accordingly:
Example:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, true));
buy.php
<form action="cart.php">
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="' . $variety['price']. '_'. $variety['variety'] '_'. $product['name']. '" />
</form>
I am sending the input form above to cart.php inthere I receive it like:
list($aDoor, $variety,$productname) = split('_', $_POST['price']);
$aDoor = array();
$variety = array();
$productname= // $productname is a string how can I set it up here?
foreach ($_POST['price'] as $p)
{
list($a, $b,$c) = explode('_', $p);
$aDoor[] = $a;
$variety[] = $b;
$productname =$c; // and I have put it equal to the variable $c here
}
The only problem above is receiving the index $product['name'] coming from the form in buy.php
In cart.php I have set it up to be received by $productname but as you can see this is an string not a array how can I set it up when it is an string in with the functions list() and split() it confuses me.
Ok. There's a few things wrong with your script.
1) You've not specified a method on your form tag, so by default the data will be submitted as a 'GET'. You're using $_POST in your script, so those values will be blank and the foreach loop will fail as $_POST['price'] doesn't exist.
2) You're naming the checkbox as "price[]". The [] tells PHP that there will be multiple values submitted with this same name, so that $_GET['price'] will be an array. Your first few lines of code will then fail, as split works on strings, not arrays. You'll end up with the following values assigned
$aDoor = "Array"
$variety = NULL;
$productname = NULL;
PHP attempts to convert your $GET['price'] array to a string, but this defaults to just coming back as the string 'Array', and there's no "" values in there, so the rest of the list() variables having nothing to be assigned to them, so they become null.
3) Split's been deprecated and will be removed in PHP 6, so use explode() instead (as you do just a few lines later)
4) You then immediately trash those values by assigning empty arrays for $aDoor and $variety, so in effect the split line was useless
The foreach loop looks fine, though you'll want to assign to a $productname array, instead of a string, so use $productname[] = $c;
5) I would, however, not store the data you're explode()ing in three seperate arrays. It would make more sense to
store it like this:
$products = array();
foreach($_POST['price'] as $p) {
list($a, $b, $c) = explode('_', $p);
$products[] = array('aDoor' => $a, 'variety' => $b, 'productname' => $c);
}
This way you don't have to pass around 3 arrays (or make them 'global') in any functions that use this data, you can pass just a single variable (ie: updateInventory($products[7]); )
5) If this shopping cart script was released into the wild, it could be a gaping security hole on the server. What would stop someone from constructing their own price by passing in something like "$0.00_fire engine red-ferrari" as the price field? I've always wanted a free Ferrari, and round-tripping pricing data through the user's browser is a nice way to get it. Never, ever, trust a client to NOT hack up critical data, such as its price.
$productname = '';
If you don't specify the method attribute of the form, the default is GET. In your script you are using POST, try putting POST method to your form:
<form action="cart.php" method="post">
Secondly, even if $productname is a string but you can convert it to array (like you have done for other vars) by suffixing it with [], so your code becomes:
$aDoor = array();
$variety = array();
$productname = array();
foreach ($_POST['price'] as $p)
{
list($a,$b,$c) = explode('_', $p);
$aDoor[] = $a;
$variety[] = $b;
$productname[] = $c;
}
Now these three arrays contains your data.