PHP Arrays and Form Values - php

PHP noob here. I am using PHP to present a supply order form. The list of supplies that can be ordered are dynamic, so I'm pulling them from a MySQL database. Here is the PHP code that is generating the HTML form fields by looping through the results of the query:
while($row = mysqli_fetch_array($itemresult))
{
echo "<input type='hidden' name='Item_ID[]' value='" . $row['Item_ID'] . "'></TD>";
echo "<TR><TD class='itemdesc'>" . $row['Item_Name'] . " </TD>";
echo "<input type='hidden' name='Item_Name[]' value='" . $row['Item_Name'] . "'></TD>";
echo "<TD>" . $row['Item_Qty'] . " </TD>";
echo "<TD class='itemprice'>" . $row['Price'] . " </TD>";
echo "<input type='hidden' name='Item_Price[]' value='" . $row['Price'] . "'></TD>";
echo "<TD><input type='text' size='3' name='Order_Qty[]'></TD>";
echo "<TD><input type='checkbox' name='Off_Day[]'></TD>";
}
I have no experience using arrays, however it makes sense that I need these form values passed to my process.php file in an array format. For now, the purpose of my process.php is to simply print a list of Item_Name and the associated Order_Qty by themselves, pretty much like:
Pencils 10
Pens 7
and on and on.
Being new to arrays and PHP, I have no idea how to accomplish this in my process.php files and would appreciate some guidance. Thanks!
+++++++++++++++++++++++++++++++++++++++++++++++
*#yknivag*
Thank you! That helps me understand me the structure. I've been testing various foreach examples online, am hitting a roadblock and could use some additional help. My array result looks like this.
[Item_Name] => Array (
[0] => One Item
[1] => Second Item
[2] => Third Item
[3] => Fourth Item )
[Item_Price] => Array (
[0] => 0.00
[1] => 64.50
[2] => 110.00
[3] => 38.45 )
How do I reference a particular value in the array, such as 'Second Item'? I can't seem to figure out the syntax for referencing a particular item. For instance, this statement returns no data.
echo "Item: " . $_POST[Item_Name] . "<BR>";
What would also be helpful, is to know how to display corresponding array items such as 'Second Item' and '64.50' together?
The following foreach loop seems like it should do the trick, however it doesn't return any data either.
foreach ($myarray as $key => $value)
{
echo "<p>".$key." ".$value."</p>";
}
Everything I've read says this should give me what I want, and I'm confused as to why it's returning nothing.

In your process.php file begin with:
<?php
print "<pre>" . PHP_EOL;
print_r($_POST);
print "</pre>" . PHP_EOL;
?>
Then you will see the structure of the data which is being sent back and that should help you to work out how to process it.
Once you have the structure, examine the foreach command.

You want an associative array
array("pencil" => 9.99, "pen" => 3.23, "paper" => 21.11)
If you are submitting your form through AJAX, you would use JavaScript to post the values to your PHP page.
var pencil = document.getElementById("pencil").value;
var pen = document.getElementById("pen").value;
var paper = document.getElementById("paper").value;
$.post("process.php", {pencil: pencil, pen: pen, paper: paper});
On your "process" page, you would grab the values that were posted
$pencil = $_POST["pencil"];
$pen = $_POST["pen"];
$paper = $_POST["paper"];
then build your array with the following
$myarray = array("pencil" => $pencil, "pen" => $pen, "paper" => $paper);
Edit
In your WHILE loop, build yourself an array by putting this at the end
$myarray[$name] = $price;
Then outside of the loop, encode your array into a JSON object
$myjson = json_encode($myarray, JSON_HEX_APOS);
Now that you have a JSON object, you'll need to grab it in JavaScript
var myjson = <?php echo $myjson; ?>;
Then you can do whatever you want with the key / value pairs
for(var key in myjson){
var item_name = key;
var item_price = myjson[key];
//where the magic happens
}

Related

Retrieve content from parsed json array

I have the following code that I need to be able to get each section of the array separately.
Here is the code:
$parsed = $parsed_json['forecast']['txt_forecast']['forecastday'];
foreach($parsed as $key => $value)
{
echo '<table border="1" width="200px">';
echo '<td>';
echo '<td><b>' . $value['title'] . '</td></font>';
echo '</tr>';
echo '<tr>';
echo '<tr>' .$value['fcttext'] . '</tr></font>';
echo '<td><img src=' . $value['icon_url'] . '></td>';
echo '</tr></table>';
}
What I want is to be able to get lets say the first title in the array
echo $value['title'][1]
The above is what i thought would work. But it returns just a single letter.
It should read "Saturday"
How can i go about getting it corrected?
$parsed[0]['title']; will return the first item of the array's title.
Indexing starts with 0 and not 1 (so 0 is first, 1 is second etc) - saving those bytes adds up on large projects!
As #JimL indicates, [1] gets the second item of our variable. If it's an array this is the second item of the array. As this is a string (the title) we get the second letter instead. Hope that explains it for you.

Iterate PHP Array in Form Submission

I have an HTML form that's submitting to a PHP script and send it as an email.
The problem I'm having is iterating the array and getting the output formatted into a table correctly.
My input fields look like this:
<input class="form-control" type="text" name="alternate[][qty]" />
<input class="form-control" type="text" name="alternate[][height]" />
I am iterating the array like this:
if ( isset( $_POST['alternate']))
{
foreach($_POST['alternate'] as $alt)
{
$message .= "<tr><td>" . $alt['qty'] . "</td><td>" . $alt['height'] . "</td></tr>";
}
}
I'm getting the correct values from the array but they are not formatted correctly. I am looking for an output something like this:
123 45
but instead it breaks across two rows like this:
How can I get both values on the same line?
EDIT:
Using
echo '<pre>';
print_r($_POST['alternate']);
echo '</pre>';
I get
Array
(
[0] => Array
(
[qty] => 54
)
[1] => Array
(
[height] => 5
)
[2] => Array
(
[qty] => 34
)
[3] => Array
(
[height] => 5
)
[4] => Array
(
[qty] => 36
)
[5] => Array
(
[height] => 45
)
...
)
which makes it look like I actually have 6 arrays...? That would explain why I'm getting each cell on a separate row, but I still don't understand how to fix it...
You're iterating through every element in $_POST['alternate'] and creating a row for each iteration. There are two elements, thus two rows.
There's no need to iterate since you already know which elements you'll get:
if ( isset( $_POST['alternate']))
{
$message = "<tr><td>{$_POST['alternate']['qty']}</td><td>{$_POST['alternate']['height']}</td></tr>";
}
Give this a shot, I hope that's what you're opting for.
if(isset($_POST['alternate']))
{
$message = "<tr>";
foreach($_POST['alternate'] as $alt)
{
if(isset($alt['qty']))
$message .= "<td>" . $alt['qty'] . "</td>";
elseif(isset($alt['height']))
$message .= "<td>" . $alt['height'] . "</td>";
}
$message .= "</tr>";
}
This gave me <tr><td>123</td><td>45</td></tr>.
EDITED SOLUTION
This script actually takes care of <tr> tags inside of the loop.
if(isset($_POST['alternate']))
{
foreach($_POST['alternate'] as $alt)
{
if(isset($alt['qty']))
$message .= "<tr><td>" . $alt['qty'] . "</td>";
elseif(isset($alt['height']))
$message .= "<td>" . $alt['height'] . "</td></tr>";
}
}
Try it out and let me know.
Your HTML actually declares separate array entries. You need to group them by defining keys for the array. Something like:
<input class="form-control" type="text" name="alternate[0][qty]" />
<input class="form-control" type="text" name="alternate[0][height]" />
Then the next group of fields uses "1" and so on.

Unserialize query (array) data is not working

I gave recently created a search function with checkboxes that queries for the submitted checkbox values and returns those values into a table.
The problem however is that certain of the checkbox values (in the database) are serialized. When i display the query result variable in a foreach for every checkbox value, it returns serialized characters. Obviously i want to just show the string without the weird characters.
The original piece of code, where the entire serialized characters are returned was as follows:
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo"<td>" . $value . "</td>";
}
echo "</tr>";
}
}
echo '</table>';
So to just display the string of the database value i try'd to use the unserialize function (the $tmp is by the way the variable in which the query results are being stored). There were however several issues with this, namely:
echo doesnt work with unserialize
the database and query can also return non-serialized data (so the $tmp variable can contain a. serialized values with the weird characters and b. just a non-serialized normal string).
Because the unserialize function also gets the 'normal' strings, those normals trings will be outputted as blanks..
For some reason, the output of the arrays/unserialized data (with print_r) displays not the string but rather the entire array name, like this: Array ( [0] => [1] => Netherlands ).
The code below is how i try'd to unserialize the data:
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo "<td>";
$b=unserialize($value);
print_r($b);
echo "</td>";
}
echo "</tr>";
}
}
echo '</table>';
Though, like said before, the above code shows the entire array name and the 'normal' strings of the database that are also queried are displayed as blanks.
So what to do to get this fixed?
Thank you in advance
Php unserialize can return several things including an array which is your case. Do this
foreach($tmp[$i] as $key=>$value){
echo "<td>";
$b=unserialize($value);
if(is_array($b)){
//this assumes your array is always like this Array ( [0] => [1] => Netherlands )
echo $b[1];
}
else{
echo $value;
}
echo "</td>";
}

Insert an array in a database

I have a wordpress page where i got a option list filled with an array. Code below:
$option = array("Zomervakantie", "Goede vrijdag", "Vrijdag na HV", "Bijzonder verlof", "Medisch", "Leeftijdsuren", "Bapo-uren", "EHBO-uren", "Compensatieverlof",
"3 en 4e paasdag", "Meivakantie", "Herfstvakantie");
echo "Selecteer hier je type verlof: ";
echo "<br />" . "<br />";
echo "<select id='selectList' name='selectList'>";
foreach ( $option as $list )
{
echo "<option value='" . $list . "'>" . $list . "</option>";
}
echo "</select>";
When i'm trying to insert this the whole query doesn't work anymore.
This is a part of my query: $wpdb->insert('table',array(column=>$_POST['selectList']));
I'm using a wordpress query.
Anyone knows what the correct way to insert this in a database? i'm using phpmyadmin.
Thanks in advance!
My knowledge of wordpress is very limited.
However, this appears to be invalid PHP to me (unless 'column' is a wordpress constant):
$wpdb->insert('table',array(column=>$_POST['selectList']));
Try
$wpdb->insert('table',array('column'=>$_POST['selectList']));
If you don't already, you should get an IDE which points out syntax errors as you type, such as Netbeans or PHPStorm. I assume Eclipse also does this.
You can insert a array directly to database just use these code
$option = array("Zomervakantie", "Goede vrijdag", "Vrijdag na HV", "Bijzonder verlof", "Medisch", "Leeftijdsuren", "Bapo-uren", "EHBO-uren", "Compensatieverlof",
"3 en 4e paasdag", "Meivakantie", "Herfstvakantie");
$wpdb->insert('table',$option);
If you want to store an array in a database, you can serialize it, or encode it in JSON (there is a PHP function for JSON encoding). It becomes a String, which you can store easily.
It works with objects too.
Example :
$array = array("1" => "PHP code tester Sandbox Online",
"foo" => "bar", 5 , 5 => 89009,
"case" => "Random Stuff",
"PHP Version" => phpversion()
);
$string = json_encode ($array);
echo($string);
echo "\n";
$array2 = json_decode($string);
foreach( $array2 as $key => $value ){
echo $key."\t=>\t".$value."\n";
}

Managing the adds and removes from arrays

I am working with a couple of arrays that are stored in sessions. The purpose is to be able to add and remove objects from the arrays which will contain recipients to messages posted. It SEEMS to be working okay but with some quirks.
This code allows objects to be added;
while($row = mysqli_fetch_array($result))
{
$contact = $row['contact'];
$userid = $row['userid'];
echo "<tr>";
echo "<td><a href='mypagepost.php?contact=$userid&recipient=$contact' STYLE='TEXT- DECORATION: NONE'><font color=#808080>" . $row['contact'] . "</a></font></td>";
echo "</tr>";
$contact_count++;
}
And this one gives me the ability to send to another page for removal from the respective arrays.
<?php
$isBefore = array();
foreach ($_SESSION['contactlist'] AS $key => $rec)
{
if (!in_array($rec, $isBefore)) {
$isBefore[] = $rec;
echo "<font color=#808080><a href='removerecipient.php?contact=" . $_SESSION['recipientlist'][$key] . "&recipient=$rec' STYLE='TEXT-DECORATION: NONE'>
<font color=#808080>" . $rec . " </a></font>";
}
}
?>
This references a page with the following;
unset($_SESSION['recipientlist'][array_search($contact, $_SESSION['recipientlist'])]);
unset($_SESSION['contactlist'][array_search($recipient, $_SESSION['contactlist'])]);
So, I'm just starting to learn how to use arrays effectively so please forgive me for asking an obtuse question or two. When I click on a recipient just once to add them to the arrays, it works fine. I find that I can click on recipients in a contact list multiple times and the array still allows them to be added over and over again (although it doesn't print them out in the list). When I go to remove them by clicking on their name, I have to click them over and over again until they're gone. How can I set up a situation where it only gets added once and that's it? The other question I have is that after I remove all recipients from an array, I'm still left with an index number with no value. The print looks like this for both arrays (this is after adding and removing three recipients from the list;
Array ( [3] => )
Array ( [3] => )
The indexes don't apear to have a value associated with them, no idea what this means.
You could create a $_SESSION and check to see
if(isset($_SESSION['nameHere'])){
//do your thing here
}
, or make a variable like
$varName = 0;
and when the form is submitted
if(isset($_POST['submitButtonName'])){
if($varName === 0){
$varName = 1;
//do you thing here
}
}
. That $_POST would be a $_GET if your <form method='get' in your HTML.

Categories