Building a php multidimensional array from form elements - php

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>

Related

form checkbox group in php

im writing a code in php that need to take a data from html form.
i have few radio bottom and few checkbox bottom.
should i have for every bottom/label do varieble in php?
for example:this is from html
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" name="cats">חתולים<br/>
<input type="checkbox" name="dogs">כלבים<br/>
<input type="checkbox" name="hamsters">אוגרים<br/>
<input type="checkbox" name="goldfish">דגי זהב<br/>
<input type="checkbox" name="human">בני אדם
</td>
</tr>
for php:
if (isset($_POST["name"]))
{
$userName = $_POST["name"];
$userYearOfBirth = $_POST["yearOfBirth"];
$soulmate = $_POST["radio"];
}
It would be better to group the checkbox choices so you can access them as an array on the server in PHP. Additionally, move the name of the choice into the value of the checkbox. The new "name" will be whatever you want to call the checkbox group. I am using Animals for this example:
<form name="your-form-name" action="your-form-action-url" method="post">
<table>
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" value="cats" name="animals[]">חתולים<br/>
<input type="checkbox" value="dogs" name="animals[]">כלבים<br/>
<input type="checkbox" value="hamsters" name="animals[]">אוגרים<br/>
<input type="checkbox" value="goldfish" name="animals[]">דגי זהב<br/>
<input type="checkbox" value="human" name="animals[]">בני אדם
</td>
</tr>
</table>
<button type="submit">Submit</button>
</form>
On the server-side if users select more than one animal, all choices will be available in an array like this:
Array
(
[0] => cats
[1] => dogs
[2] => hamsters
[3] => goldfish
[4] => human
)
If they just select one, it'll still be an array:
Array
(
[0] => cats
)
Either way getting the results as an array lets you do something similar with the results whether they chose one or many choices from the list.
You can loop through all the choices and do whatever you need to with the data:
if (isset($_POST['animals'])) {
$animals = $_POST['animals'];
foreach ($animals as $key => $value) {
// do something with each $value .. maybe add to a database? echo back to user?
}
}
You actually don't need any new variables. You can use $_POST array as the variables.
Example (form side):
<form method="post">
<input type="text" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
echo $_POST['test']; // This will echo the input that named "test".
?>
The example above is valid for every method and input types.
In your case, your checkboxes will output "true" or "false" (Unless you define a value for the checkbox. If you define a value to it, it will output the defined value if the checkbox is checked.).
Example (form side):
<form method="post">
<input type="checkbox" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
if ($_POST['test'] === true)
echo "Yay! The checkbox was checked!";
else
echo "Oops! The checkbox wasn't checked!";
?>

pairing input same name array in PHP

I have two inputs as follows:
<form method="post" action="#">
<input type="text" name="prod[][prod]"><input type="text" name="prod[][qty]">
<input type="text" name="prod[][prod]"><input type="text" name="prod[][qty]">
/* The second input set was generated dynamically via jQuery. */
</form>
I want to pair each product with its' quantity with multidimensional array with following codes (thanks to #Styphon):
$works = $_POST['prod'];
foreach ($works as $work => $value) {
echo $value['prod'] ." ". $value['qty'] ."<br>";
}
However, the results was weird as follows
aa
11
bb
22
Appreciated if someone can help on this.
You need a multidimensional array. Something like this:
<form>
<input type="text" name="prods[0][prod]">
<input type="text" name="prods[0][qty]">
<input type="text" name="prods[1][prod]">
<input type="text" name="prods[1][qty]">
</form>
Then in PHP you can access the multidimensional array using $_POST['prods'], you can loop through each one using a foreach like this:
foreach ( $_POST['prods'] as $i => $arr )
{
echo "$i is prod {$arr['prod']} and qty {$arr['qty']}<br>";
}

Update multiple columns with multiple values in one single table

I'm making a very simple stock control system. In the page that the user will be able to do the updates, I'm listing all the contents in the table and putting everything in text fields, like the image.
So, the user should just change what he wants and when he clicks on submit, it would update every row in the table, with its respective value. But my code isn't working. I don't know how to make this kind of update and I'm sure it's wrong, because it doesn't even work. Here my form:
<form action="update_pcs.php" method="POST">
<label>Peça</label>
<label for="txtQtd" id="qtd">Qtd.</label>
<br/>
<?php foreach($rtn as $pcs){ ?>
<input type="text" name="txtNome[]" id="txtNome" value="<?=$pcs['pc_nome']?>" />
<input type="text" name="txtQtd[]" id="txtQtd" value="<?=$pcs['num']?>"/>
<input type="hidden" name="txtId[]" id="txtId" value="<?=$pcs['id']?>" />
<br />
<br />
<?php } ?>
<br />
<br />
<input type="submit" value="Enviar" name="btnEnvia" />
</form>
And my file update_pcs.php, which should do the update in the table.
<?php
include_once 'mdl.php';
$conexao = new modelDB();
$qtd = $_POST['txtQtd'];
$nom = $_POST['txtNome'];
$id = $_POST['txtId'];
/*This makes the $dados array keep in the value ['nome'] another array, the value ['qtd'] another array and ['id'] another array*/
$dados = array('nome'=>$nom,
'qtd'=>$qtd,
'id'=>$id);
foreach($dados as $dado){
/* I'm doing it that way but it isn't working */
$nomeAt = $dado['nome'];
$qtdAt = $dado['qtd'];
$id = $dado['id'];
$conexao->alteraDb("update pcs_estq set pc_nome ='{$nomeAt}', num = '{$qtdAt}' where id = '{$idAt}'");
}
My function must be right because when I change the php variables for values, it works. How could I make this right?
With sending array names in your html form, you will receive array post variables.
First change your form like below to help posting more appropriate data.
<input type="text" name="values[<?=$pcs['id']?>][Nome]" id="txtNome" value="<?=$pcs['pc_nome']?>" />
<input type="text" name="values[<?=$pcs['id']?>][Qtd]" id="txtQtd" value="<?=$pcs['num']?>"/>
<input type="hidden" name="values[<?=$pcs['id']?>][id]" id="txtId" value="<?=$pcs['id']?>" />
Actually this way you don't need to send id but i am sending for simple explanation.
Now you post, you'll receive an array like :
values => array (
1 => array (
'id'=> 1,
'Nome' => 'Some text',
'Qtd' => 1
),
2 => ....
)
Now you can get your data and insert your db.
$values = $_POST['values'];
foreach ($values as $dado) {
$nomeAt = $dado['Nome'];
$qtdAt = $dado['Qtd'];
$id = $dado['id'];
By the way, i strongly recommend using pdo, if not please make sure you validate your data before passing database query.

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 />';
}

Merging PHP arrays

I am working on a project at the moment, that allows the user to create any number of news headlines, articles and images, the only rule with this system is that a headline must have an article and an image. My question is on my form when I submit I get 2 arrays one is the $_POST and the other is $_FILES.
$_POST
Array
(
[campaign_title] => Another multiple test
[campaign_keyword] => Another multiple test
[introduction] => Another multiple test
[campaign_headline] => Array
(
[0] => Another multiple test headline 1
[1] => Another multiple test headline 2
)
[article] => Array
(
[0] => Another multiple test article 1
[1] => Another multiple test article 2
)
[save_multiple] => Save
)
$_FILES
Array
(
[article_image] => Array
(
[name] => Array
(
[0] => Intro-artists.gif
[1] => textbg1.png
)
[type] => Array
(
[0] => image/gif
[1] => image/png
)
[tmp_name] => Array
(
[0] => /private/var/tmp/phpwDAkGJ
[1] => /private/var/tmp/phpmvrMDg
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 2841
[1] => 56506
)
)
)
Basically the method after submitting the form is the data is saved to a database, the 3 items of the post are saved in one table, the headlines and articles are saved in another table (sent with the id of the row just inserted) and then finally the images are saved, again sent with id of the first saved row.
I am having trouble understanding how I make sure the right images gets saved with the right ID, the DB saves are done by looping through the headlines and articles, but as the images are in a different array I cannot do this and make sure they are getting saved with right foreign id, can I merge the files into the post? Currently the solution I have for the headlines and articles is this,
foreach ($data['campaign_headline'] as $key => $headline) {
addMailerMultipleRelatedContent($mailerId, $headline, $data['article'][$key]);
}
function addMailerMultipleRelatedContent($mailerId, $headline, $article) {
extract($data);
//die(print_r($id));
$id = addRelatedMultipleContent($data['introduction'], $headline, $article,
$mailerId, mktime(), mktime());
}
function addRelatedMultipleContent($introduction, $headline, $content,
$mailer_id, $created_at, $updated_at){
$query = "INSERT INTO `mailer_content` (`id`, `introduction`, `headline`,
`content`, `mailer_id`,`created_at`, `updated_at`) VALUES ";
$query .= "(NULL, '" . makeSafe($introduction) . "', '" .
makeSafe($headline) . "', '" . makeSafe($content) . "', '" .
makeSafe($mailer_id) . "', " . makeSafe($created_at) . ", " .
makeSafe($updated_at) . ");";
$result = runInsert($query, __FUNCTION__);
//die(print_r($result));
return $result;
}
Is there away for me to work with images at the same time?
EDIT:
The HTML form,
<form method="post" action="/admin/editmultiple" enctype="multipart/form-data">
<fieldset class="toplined">
<label>Campaign Title</label>
<input type="text" name="campaign_title" value="<?echo (isset($mailers['mailer_title'])) ? $mailers['mailer_title'] : $_POST['campaign_title'];?>" class="extrawideinput" />
</fieldset>
<fieldset class="toplined">
<label>Campaign Type:</label>
<label>Multiple</label>
</fieldset>
<fieldset class="toplined">
<label>Campaign Keyword:</label>
<div class="forminputblock">
<input type="text" name="campaign_keyword" value="<?echo (isset($mailers['mailer_header'])) ? $mailers['mailer_header'] : $_POST['campaign_keyword'];?>" class="extrawideinput" />
</div>
</fieldset>
<fieldset class="toplined">
<label>Introduction</label>
<div class="forminputblock">
<input type="text" name="introduction" value="<?echo (isset($mailers['introduction'])) ? $mailers['introduction'] : $_POST['introduction'];?>" class="extrawideinput" />
</div>
</fieldset>
<fieldset class="toplined">
<label>Headline</label>
<div class="forminputblock">
<input type="text" name="campaign_headline[]" value="<?echo (isset($mailers['headline'])) ? $mailers['headline'] : $_POST['campaign_headline'];?>" class="extrawideinput" />
</div>
</fieldset>
<fieldset class="toplined">
<label>Image:</label>
<input type="file" name="article_image[]">
</fieldset>
<fieldset class="toplined">
<label>Story:</label>
<div class="forminputblock">
<textarea name="article[]" class="js_editable_textarea deeptext" rows="1" cols="1"><?echo (isset($mailers['content'])) ? $mailers['content'] : $_POST['article'];?></textarea>
</fieldset>
<div id="result">
</div>
<fieldset class="toplined">
+ Add Another New Article
</fieldset>
<fieldset class="toplined">
<input type="submit" name="save_multiple" value="Save" />
</fieldset>
</form>
With the same key you use to access the articles sub array, you can access the different fields in the $_FILES array. Obviously you can merge the two arrays, but it isn't necessary for you to work with them.
Also, you should note that you have to copy the actual data from the temporary location to where ever you would like to permanently store it. Make sure to use the [is_uploaded_file()][1] and [move_uploaded_file()][2] methods to prevent potential attacks via file uploads.
[1]: http://www.php.net/manual/en/function.is-uploaded-file.php is_uploaded_file()
[2]: http://www.php.net/manual/en/function.move-uploaded-file.php move_uploaded_file()
I'm not sure that you would want to merge the two arrays, as you need to perform different actions on each array.
With the $_FILES array, the uploaded images will be stored in a temporary location, the images need to be moved to a more permanent location before being referenced in your database.
EDIT: I've just recoded you an entire example of how it could easily work. (uses jquery as an example)
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var position = 1;
$(".add").click(function(){
var parent = $(this).parent();
var newField = $(this).parent().clone(true).insertAfter(parent);
/* title */
var newName = 'articles['+ position + '][title]';
newField.children(".name").attr("name", newName);
/* content */
newName = 'articles['+ position + '][content]';
newField.children(".content").attr("name", newName);
/* content */
newName = 'articles['+ position + '][checkbox]';
newField.children(".checkbox").attr("name", newName);
newField.slideDown();
position++;
});
});
</script>
<h1>example</h1>
<form action="" method="post">
<fieldset class="article">
<label style="display:block">Article title</label>
<input type="text" name="articles[0][title]" value="" class="name" />
<label style="display:block">Article content</label>
<textarea name="articles[0][content]" cols="40" rows="10" class="content"></textarea>
<label style="display:block">Checkbox</label>
<input type="checkbox" name="articles[0][checkbox]" value="1" class="checkbox" />
<br />
add new after
</fieldset>
<br />
<input type="submit" value="submit" name="submit" />
</form>

Categories