Associate Arrays with PHP code - php

I am learning php and having trouble understanding how to use an associate arrays with user inputs. I will eventually need to sort my array by a key value but for now I just dont know if I am doing it correctly. The examples in the book didn't show how to get a user input and use it in an array just predetermine values. Can someone please help me and tell me if I on the right track. I understand I need to use the $_POST method to get the information for the array but I just cant figure out how to use it. When i upload what i have i keep getting error
<HTML>
<HEAD>
<TITLE>Student Form</TITLE>
</HEAD>
<BODY>
<FORM METHOD="post" ACTION="final_project.php">
<P>Please enter your name: <INPUT TYPE="text" NAME="txtname" SIZE= 10></P>
<P>Please enter your id: <INPUT TYPE="text" NAME="txtid" SIZE= 10></P>
<P>Please enter your address: <INPUT TYPE="text" NAME="txtaddress" SIZE= 10></P>
<P>Please enter your cell phone number: <INPUT TYPE="text" NAME="txtcell" SIZE= 10></P>
<P>Please enter your Major: <INPUT TYPE="text" NAME="txtmajor" SIZE= 10></P>
<P>Please enter your E-mail address: <INPUT TYPE="text" NAME="txtemail" SIZE= 10></P>
<P><INPUT TYPE="submit" NAME="submit" VALUE="Submit"></P>
</FORM>
<?php
$txtname = $_POST['txtname'];
$txtid = $_POST['txtid'];
$txtaddress = $_POST['txtaddress'];
$txtcell = $_POST['txtcell'];
$array = array(txtname=>$txtname, txtid=>$txtid, txtaddress=>$txtaddress,
txtcell=>$txtcell);
for each ($txtid as $key => $array){
echo "Your first name is ".$txtname.", id number is ".$txtid[$key].", your address is
".$txtaddress.", phone number is ".$txtcell.".";
}
?>
</BODY>
</HTML>
NEW UPDATE:
$txtname[0] = $_POST['txtname'];
$txtid[1] = $_POST['txtid'];
$txtaddress[2] = $_POST['txtaddress'];
$txtcell[3] = $_POST['txtcell'];
$txtmajor[4] = $_POST['txtmajor'];
$txtemail[5] = $_POST['txtemail'];
$student = array('txtname'=>$txtname, 'txtid'=>$txtid, 'txtaddress'=>$txtaddress,
'txtcell'=>$txtcell, 'txtmajor'=>$txtmajor, 'txtemail'=>$txtemail);
foreach ($student as $key => $txtname){
print_r ($student[$key]);
}
Array ( [0] => Amanda ) Array ( [1] => 12 ) Array ( [2] => 123 West Main Street ) Array ( [3] => 888-888-8888 ) Array ( [4] => CIS ) Array ( [5] => email#email.com )
I have updated the code. I cant get it to print out my array correctly.
I want it to be = Array( [0] => Amanda) [1]=>12 [2]=> 123 west main street...) what am i doing wrong?

The PHP manual for "foreach" says to do it like this:
foreach (array_expression as $key => $value)
But you have it like this:
for each ($txtid as $key => $array){ ... }
My guess is you want to replace that whole part with this:
foreach ($array as $key => $txtid ) {
echo "your $key is $txtid ";
}

I think it is not neccessary to to an array to get informations, you can just do like this :
<?php
// your form
$txtname = $_POST['txtname'];
$txtid = $_POST['txtid'];
$txtaddress = $_POST['txtaddress'];
$txtcell = $_POST['txtcell'];
echo "Your first name is ".$txtname.", id number is ".$txtid[$key].", your address is
".$txtaddress.", phone number is ".$txtcell.".";
?>

Related

item post with multiple phone numbers

This request is from a non programmer. An Osclass item post php form code sample is given below.
<?php
$action = 'item_add_post';
$prepare['s_phone_1'] = del_get_session('sPhone1') <> '' ? del_get_session('sPhone1') : #$item_extra['s_phone_1'];
?>
<div class="input-box">
<input type="tel" id="sPhone" name="sPhone1[]" value="" />
</div>
<div class="input-box">
<input type="tel" id="sPhone" name="sPhone1[]" value="" />
</div>
<div class="input-box">
<input type="tel" id="sPhone" name="sPhone1[]" value="" />
</div>
<?php
$prepare = $_POST['sPhone1'];
?>
<input type="hidden" name="sPhone1" value="<?php echo htmlentities(serialize($prepare['s_phone_1']));?>">
functions.php page has below code also.
function del_update_fields($item) {
if(!isset($item['pk_i_id']) || $item['pk_i_id'] <= 0) {
return false;
}
if(Params::existParam('sSold')) {
$fields = array(
's_phone' => (Params::getParam('contactPhone') <> '' ? Params::getParam('contactPhone') : Params::getParam('sPhone')),
's_phone_1' => Params::getParam('sPhone1'),
'i_condition' => Params::getParam('sCondition'),
'i_negotiable' => Params::getParam('sNegotiable'),
'i_transaction' => Params::getParam('sTransaction'),
'i_sold' => (Params::getParam('sSold') == 'on' ? 1 : Params::getParam('sSold'))
);
} else {
$fields = array(
's_phone' => (Params::getParam('contactPhone') <> '' ? Params::getParam('contactPhone') : Params::getParam('sPhone')),
's_phone_1' => Params::getParam('sPhone1'),
'i_condition' => Params::getParam('sCondition'),
'i_negotiable' => Params::getParam('sNegotiable'),
'i_transaction' => Params::getParam('sTransaction')
);
}
Item::newInstance()->dao->update(DB_TABLE_PREFIX.'t_item_delta', $fields, array('fk_i_item_id' => $item['pk_i_id']));
}
Screenshot of the db table
Requirement is to store phone numbers in above 3 name="sPhone1[]" inputs in "s_phone_1" as below example.
0091222222222;0091333333333;0091666666666;
But it stores N; in mysql. Need your help to correct above code to pass these numbers as an array. And later, need to get them back in to 3 lines as below in another page.
Phone 1: 0091222222222
Phone 2: 0091333333333
Phone 3: 0091666666666
Thanks in advance..
you are getting values in the array and now these array values you want in "s_phone_1"
use this code to get value in "s_phone_1"
here you can store $phonenumbers in your database
$phonenumbers = implode(";",$_POST['sPhone1']);
//echo $phonenumbers;
output
09874563214;09874563214;09874563214
now for getting value as per your requirement
get value from the database and store it in $phonenumbers
$getPhoneNumbers = explode(";",$phonenumbers);
echo "Phone 1:" .$getPhoneNumbers[0]."<br>";
echo "Phone 2:" .$getPhoneNumbers[1]."<br>";
echo "Phone 3:" .$getPhoneNumbers[2]."<br>";
output
Phone 1:09874563214
Phone 2:09874563214
Phone 3:09874563214

User input from 3 textboxes to be inserted into PHP-array [duplicate]

This question already has answers here:
Get all variables sent with POST?
(6 answers)
How to grab all variables in a post (PHP)
(5 answers)
How do I get the key values from $_POST?
(6 answers)
Retrieve post array values
(6 answers)
How to get an array of data from $_POST
(3 answers)
Closed 5 years ago.
I have an HTML-form with 3 inputs of type text and one input of type submit, where a name of an animal is to be inserted into each textbox. The data should then be inserted into a PHP-array.
This is my HTML-form:
<form action="Test.php" method="post" name="myForm" id="myForm">
<input type="text" placeholder="Enter animal one..." name="animal1" id="animal1">
<input type="text" placeholder="Enter animal two..." name="animal2" id="animal2">
<input type="text" placeholder="Enter animal three..." name="animal3" id="animal3">
<input type="submit" value="Submit" name="send" id="send">
</form>
And this is my much experimental PHP-code:
<?php
if (isset ($_POST["send"])) {
$farmAnimals = $_POST["animal1"];
$farmAnimals = $_POST["animal2"];
$farmAnimals = $_POST["animal3"];
}
// As a test, I tried to echo the saved data
echo $farmAnimals;
?>
This does not work, as the data doesn't magically turn into an array, unfortunately, which I thought it would.
I have also tried this:
<?php
if (isset ($_POST["send"])) {
$farmAnimals = $_POST["animal1", "animal2", "animal3"];
}
echo $farmAnimals;
?>
This gives me an error message. How can I insert this data into a PHP-array?
First initialize the $farmAnimals as array, then you can push elements
if (isset ($_POST["send"])) {
$farmAnimals = array();
$farmAnimals[] = $_POST["animal1"];
$farmAnimals[] = $_POST["animal2"];
$farmAnimals[] = $_POST["animal3"];
print_r($farmAnimals);
}
Try this:
$string = "";
foreach($_POST as $value){
$string .= $value . ",";
}
Or this:
$string = implode(',', $_POST);
If you change the text field names to animal[] then you have an array of animal names when it is posted
<form action='Test.php' method='post'>
<input type='text' placeholder='Enter animal one...' name='animal[]' />
<input type='text' placeholder='Enter animal two...' name='animal[]' />
<input type='text' placeholder='Enter animal three...' name='animal[]' />
<input type='submit' value='Submit' name='send' id='send'>
</form>
You can then process that array in php easily for whatever end purpose you have - the output of which would be like this:
Array
(
[animal] => Array
(
[0] => giraffe
[1] => elephant
[2] => rhinocerous
)
[send] => Submit
)
To access these animals as an array in their own right you could do:
$animals=array_values( $_POST['animal'] );
Try naming your input fields like this:
<form action="Test.php" method="post" name="myForm" id="myForm">
<input type="text" placeholder="Enter animal one..." name="animal[0]" id="animal1">
<input type="text" placeholder="Enter animal two..." name="animal[1]" id="animal2">
<input type="text" placeholder="Enter animal three..." name="animal[2]" id="animal3">
<input type="submit" value="Submit" name="send" id="send">
</form>
This way you be able to access those values in your PHP code like this:
if(isset($_POST["send"])) {
$farmAnimals = $_POST["animal"];
}
var_dump($farmAnimals);
// Array( [0] => Animal1, [1] => Animal2, [2] => Animal3 )
// Where Animal1,... are the values entered by the user.
// You can access them by $farmAnimals[x] where x is the desired index.
Tip: You can use empty() to check a variable for existance and if it has a "truthy" value (a value which evaluates to true). It will not throw an exception, if the variable is not defined at all. See PHP - empty() for details.
Futher reference about the superglobal $_POST array, showing this "array generating name" approach: https://secure.php.net/manual/en/reserved.variables.post.php#87650
Edit:
I just saw, that you actually overwrite your $farmAnimals variable each time. You should use the array(val1, val2, ...) with an arbitray amount of parameters to generate an numeric array.
If you prefer an associative array do this:
$myArray = array(
key1 => value1,
key2 => value2,
....
);
To append a value on an existing array at the next free index use this syntax:
// This array contains numbers 1 to 3 in fields 0 to 2
$filledArray = array(1,2,3);
$filledArray[] = "next item";
// Now the array looks like this:
// [0 => 1, 1 => 2, 2 => 3, 3 => "next item"]

A little help deleting value from an global variable

I am trying to fetch some form data but something interrupts,
<?php
if(isset($_POST['submit'])){
$data = $_POST;
}
?>
<form action = "page.php" method="post">
Username<input type="username" name="username"/><br/>
Password<input type="text" name="password"/><br/>
<input type="submit" name="submit"/>
</form>
okay, the above outputs to
Array ( [username] => '' [password] => '' [email] => '' [submit] => Submit )
Okay, if i am to send this into database. i should be sending it without the key submit and value submit. How do you do it?
Unset it.
if ( isset($_POST['submit']) ) {
unset($_POST['submit']);
}
A better practice would be to save it to a new variable and make changes there.

Building a php multidimensional array from form elements

I'm trying to get a multidimensional array to store the info from three separate elements (caption, image, and subfolder). The three elements are descriptions from photos that individuals may upload onto my site. I've built an initial page that asks the visitor how many photos they intend to upload and from which country(an input type=select). Based upon their response on that initial form, the second page uses a loop to generate the appropriate number of , , and elements. Once the second form is submitted the intention is to upload the info to the server which it does. The second objective is to store that information inside the multidimensional array such as below in order to upload into a MySQL table. My dilemma is in getting the image names presumably from ($_FILES['image']['name']) to insert themselves into my multidimensional array. The captions '' insert themselves into the multidimensional array as does the country name ('name=subfolder']) but not the image names. I'd greatly appreciate anyone willing to help with this.
Thank you.
Array ( [caption] => Array ( [0] => Nice Simple Picture [1] Another Nice Simple Picture=> )
[image] => [subfolder] => Array ( [0] => Italy ) [upload] => UPLOAD )
Here's a bit of how I've attempted to go about this..
<?php
$file=$_FILES['image']['name'];
$expected = array('image','subfolder','caption');
foreach ($_POST as $key => $value) {
if (in_array ($key, $expected)) {
${$key} = mysql_real_escape_string($value); }}
$sql = "INSERT INTO images (file_name, country, caption)
VALUES ('$image', '$subfolder', '$caption')";
$result = mysql_query($sql) or die (my_sql_error()); }
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" id="form1" name="form1" method="POST"
enctype="multipart/form-data">
<?php
for ($i=0; $i<$imgnumb; $i++) {
echo "<input type=\"file\" name=\"image[".$i."]\" /> <input type=\"text\"
name=\"caption[".$i."]\" /><br />"; }
?>
<br />
<input value="<?php echo $file; ?>" name="image" type="hidden" />
<input value="<?php echo $location; ?>" name="subfolder" type="hidden" />
<input value="<?php echo $_POST['caption']; ?>" name="caption" type="hidden" />
<input type="submit" name="upload" id="next" value="UPLOAD" />
</form>

PHP: Manipulating Multdimensional Array in Form Data?

I have a form that includes the first name and last name of a person. The user can add multiple people using a link, that creates new input fields via JS. Here's an example of a form that includes 2 people:
<form action="" method="post">
<input type="text" class="required" name="people[first][]" />
<input type="text" class="required" name="people[last][]" />
<input type="text" class="required" name="people[first][]" />
<input type="text" class="required" name="people[last][]" />
<input type="submit" name="submit">
</form>
I'm trying to figure out a way to insert this data into the database. I've tried using:
foreach ($_POST['people'] as $person) {
foreach ($person as $value) {
echo $value . '<br/>';
}
}
.. which results in
first name 1
first name 2
last name 1
last name 2
I'm trying to group the results somehow so I can insert a new row for each first name x + last name x combination.
Create the input elements like this:
<input type="text" name="people[0][first]" />
<input type="text" name="people[0][last]" />
<input type="text" name="people[1][first]" />
<input type="text" name="people[1][last]" />
In your PHP:
foreach ($_POST['people'] as $person) {
echo $person['first'].' '.$person['last'].'<br />';
}
$_POST['people']['first'] is an array of first names.
$_POST['people']['last'] is an array of last names.
You can merge them into an array of arrays like this:
$people = $_POST['people'];
$length = count($people['first']);
for($i = 0; $i < $length; $i++)
$temp[] = array('first' => $people['first'][$i], 'last' => $people['last'][$i]);
$people = $temp;
The resulting array in $people will be an array of associative arrays, and might look like:
Array
(
[0] => Array
(
[first] => Jim
[last] => Smith
)
[1] => Array
(
[first] => Jenny
[last] => Johnson
)
)
which is equivalent to the array you would get by modifying your HTML as bsdnoobz has shown you can do as well. Iterating through it would be the same too:
foreach ($people as $person) {
echo $person['first'] . ' ' . $person['last'] . '<br />';
}

Categories