Unset item from Array $_FILES upload - php

I have a script where users can upload multiple files (max. 8). The HTML is generated by a piece of PHP:
$max_no_img=8;
for($i=1; $i<=$max_no_img; $i++){
<div class='photo photo$i'>
<div class='new_label'>
Foto $i:
</div>
<div class='new_input'>
<input type='file' name='images[]' />
</div>
</div>";
}
So the array images[] consists of 8 values. However, every time a user submit it's form, the form is generating an Array of 8 items and by so, inserting 8 values in the database (whether they are empty or not).
So I would like to unset the empty values, copy the files to my folders and insert the link into my database. But here is the part where the errors happen.
The array of $_FILES consists of 4 things. name, tmp_name, error and size. How do I get it so a complete item (let's say images[0]) will be unset from the array so I can continue with the items which actually carry a value.
I tried this, but with no results...
unset($_FILES['images'][0])
and
unset($_FILES['images']['name'][0])
unset($_FILES['images']['tmp_name'][0])
unset($_FILES['images']['error'][0])
unset($_FILES['images']['size'][0])
Any advice how to unset a value from a $_FILES-arry?

You can just ignore them instead of processing or unsetting any items:
if (!empty($_FILES['images'])) {
for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
if (empty($_FILES['images']['name'][$i])) {
// This item is empty
echo "Item $i references an empty field.\n";
continue;
}
echo "Item $i is a valid file.\n";
}
}

You do not actually need to unset any items. Simply skip over the items that don't correspond to an uploaded file:
for($i=1; $i <= $max_no_img; $i++) {
if(empty($_FILES['images']['name'][$i])) {
continue; // that's all it takes
}
}

Related

PHP FOR loop taking values from form (post)

I have form with elements (text fields), 5 diference elements names:
name1a name1b
name2a name2b
name3a name3b
name4a name4b
name5a name5b
and php file:
for ($i = 1; $i <= 5; $i++) {
echo $i,"<br/>";
$name. $i .'a' = $_POST['name'.$i.'a'];
echo $name. $i .a;
}
It is posible read text fields with for loop or no? And pass values to sql query aswell?
you can use
extract($_POST);
like
echo $name1a;
echo $name1b;
you can access the value with the text-box names itself
It´s possible, but it´s a bad practice and I can´t recommend it you.
So, use arrays to store similar values from form (when you indexed your names, every times use arrays instead).
<input name="name[1]" ...> <!-- key isn't neccesary here, name[] will count from 0 -->
<input name="name[2]" ...>
<input name="name[3]" ...>
<?php
for ($i = 1; $i <= count($_POST['name']), $i++) {
echo $_POST['name'][$i] . '<br>'; // work directly with this variables/array, don't create duplicate vars
}
?>

removing last element from a multidimensional array in php

I have a textbox that iterates 5 times and displays values from the textbox into an array.
<form method="post" action="test.php">
<?php for($i = 0; $i < 5; $i++) {
echo "<input type='text' name='text1[]'/>";
} ?>
<input type="submit" name="confirm" value="confirm" />
</form>
<?php
$text1 = $_POST['text1'];
$count= count($text1);
if(isset($_POST['confirm'])) {
for($p = 0; $p < $count; $p++) {
echo print_r($p[$i]);
}
}
?>
I want to remove the last value (which is that repeating number 1) from the data and only display the names. The output of above is as follows:-
John1
Jack1
Peter1
Jane1
Jill1
echo print_r($p[$i]);
print_r prints content of $p[$i] and returns 1 that is passed to echo (and printed next to desired output). You don't need print_r here.
print_r sends $p[$i] to the output buffer and then it returns a boolean result, which will be true (or 1 when echoed out).
So, the solution is simply to not use print_r.
Always read the documentation when you are unsure about something. Pretty much anything you want to know about PHP can be found there.

how to get post from same name textboxes in php

I have a form with multiple textboxes which are created dynamically, now all these textboxes are of same name lets say txt, now is there any way that when form processing happens we could read all the text boxes values using $_POST method, which are of so called same name. If possible how?
You have to name your textboxes txt[] so PHP creates a numerically indexed array for you:
<?php
// $_POST['txt'][0] will be your first textbox
// $_POST['txt'][1] will be your second textbox
// etc.
var_dump( $_POST['txt'] );
// or
foreach ( $_POST['txt'] as $key => $value )
{
echo 'Textbox #'.htmlentities($key).' has this value: ';
echo htmlentities($value);
}
?>
Otherwise the last textbox' value will overwrite all other values!
You could also create associative arrays:
<input type="text" name="txt[numberOne]" />
<input type="text" name="txt[numberTwo]" />
<!-- etc -->
But then you have to take care of the names yourself instead of letting PHP doing it.
Create your text box with names txt[]
<input type='text' name='txt[]'>
And in PHP read them as
$alTxt= $_POST['txt'];
$N = count($alTxt);
for($i=0; $i < $N; $i++)
{
echo($alTxt[$i]);
}
If you want name, you could name the input with txt[name1], then you could get it value from $_POST['txt']['name1']. $_POST['txt'] will be an associative array.

checkbox's stay checked after pagination in php

Hello i want any checkbox i am gonna check, to stay checked after pagination.
here is the code:
foreach($test as $string){
$queryForArray = "SELECT p_fname,p_id FROM personnel WHERE p_id = " .$string["p_id"]. " ;" ;
$resultForArray = mysql_query($queryForArray, $con);
$rowfForArray = mysql_fetch_array($resultForArray);
?>
<td id="<?php echo $rowfForArray["p_id"]?>" onclick="setStyles(this.id)" ><?php echo $rowfForArray["p_fname"]?></td>
<td><input id="<?php echo $rowfForArray["p_id"]?>" class="remember_cb" type="checkbox" name="how_hear[]" value="<?php echo $rowfForArray["p_fname"]?>"
<?php foreach($_POST['how_hear'] as $_SESSION){echo (( $rowfForArray["p_fname"] == $_SESSION) ? ('checked="checked"') : ('')); } ?>/></td>
</tr>
<tr>
I am geting the data from a search result i have in the same page , and then i have each result with a checkbox , so that i can check the "persons" i need for $_Session use.
The only think i want is the checkbox's to stay checked after pagination and before i submit the form!(if needed i can post the pagination code, but he is 100% correct)
In the checkbox tag use the ternary operation, without that foreach inside him:
<input [...] value="<?php echo $rowfForArray["p_fname"]?>" <?php $rowfForArray["valueToCompareIfTrue"] ? "checked='checked'" : ''; ?> />
because the input already is inside of 'for' loop, then each time of the loop will create a new checkbox wich will verify if need to being check or not.
I hope I have helped you.
A few ways to tackle this:
(Straight up PHP): Each page needs to be a seperate form then, and your "next" button/link needs to submit the form everytime they click next. The submit data should then get pushed to your $_SESSION var. The data can then be extracted and used to repopulate the form if they navigate backwards as well. Just takes some clever usage of setting the URL with the proper $_GET variables for the form.
(HTML5): This will rely more on JavaScript, but basically you get rid of pagination and then just break the entire data set into div chunks which you can hide/reveal with JavaScript+CSS or use a library like JQuery.
(AJAX): Add event listeners to the checkboxes so that when a button is checked an asynchronous call is made back to a PHP script and the $_SESSION variable is updated accordingly. Again, this one depends on how comfortable you are with JavaScript.
Just keep in mind that PHP = ServerSide & JavaScript = ClientSide. While you can hack some PHP together to handle "clientside" stuff, its usually ugly and convoluted...
I did it without touching the database...
The checkbox fields are a php collection "cbgroup[]".
I then made a hidden text box with all the values which equal the primary keys of the selectable items mirroring the checkboxes. This way, I can iterate through the fake checkboxes on the current page and uncheck the checkboxes by ID that exist on the current page only. If the user does a search of items and the table changes, the selectable items remain! (until they destroy the session)
I POST the pagination instead of GET.
After the user selects their items, the page is POSTED and I read in the hidden text field for all the checkbox IDs that exist on that current page. Because PhP only tells you which ones are checked from the actual checkboxes, I clear only the ones from the session array that exist on the POSTED page from this text box value. So, if the user selected items ID 2, 4, 5 previously, but the current page has IDs 7,19, and 22, only 7, 19, and 22 are cleared from the SESSION array.
I then repopulate the array with any previously checked items 7, 19, or 22 (if checked) and append it to the SESSION array along with 2, 4, and 5 (if checked)
After they page through all the items and made their final selection, I then post their final selections to the database. This way, they can venture off to other pages, perhaps even adding an item to the dB, return to the item selection page and all their selections are still intact! Without writing to the database in some temp table every page iteration!
First, go through all the checkboxes and clear the array of these values
This will only clear the checkboxes from the current page, not any previously checked items from any other page.
if (array_key_exists('currentids', $_POST)) {
$currentids = $_POST['currentids'];
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$removeItems = explode($delimiter, $currentids);
foreach ($removeItems as $key => $del_val) {
//echo "<br>del_val: ".$del_val." - key: ".$key."<br>";
// Rip through all possibilities of Item IDs from the current page
if(($key = array_search($del_val, $itemList)) !== false) {
unset($itemList[$key]);
//echo "<br>removed ".$del_val;
}
// If you know you only have one line to remove, you can decomment the next line, to stop looping
//break;
}
// Leaves the previous paged screen's selections intact
$newSessionItems = implode(",", $itemList);
$_SESSION['materials'] = $newSessionItems;
}
}
}
Now that we have the previous screens' checked values and have cleared the current checkboxes from the SESSION array, let's now write in what the user selected, because they could have UNselected something, or all.
Check which checkboxes were checked
if (array_key_exists('cbgroup', $_POST)) {
if(sizeof($_POST['cbgroup'])) {
$materials = $_POST['cbgroup'];
$N = count($materials);
for($i=0; $i < $N; $i++)
{
$sessionval = ",".$materials[$i];
$_SESSION['materials'] = $_SESSION['materials'].$sessionval;
}
} //end size of
} // key exists
Now we have all the items that could possibly be checked, but there may be duplicates because the user may have paged back and forth
This reads the entire collection of IDs and removes duplicates, if there are any.
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$filtered = array();
foreach ($itemList as $key => $value){
if(in_array($value, $filtered)){
continue;
}
array_push($filtered, $value);
}
$uniqueitemschecked = count($filtered);
$_SESSION['materials'] = null;
for($i=0; $i < $uniqueitemschecked; $i++) {
$_SESSION['materials'] = $_SESSION['materials'].",".$filtered[$i];
}
}
}
$_SESSION['materials'] is a collection of all the checkboxes that the user selected (on every paged screen) and contains the primary_key values from the database table. Now all you need to do is rip through the SESSION collection and read\write to the materials table (or whatever) and select/update by primary_key
Typical form...
<form name="materials_form" method="post" action="thispage.php">
Need this somewhere: tracks the current page, and so when you post, it goes to the right page back or forth
<input id="_page" name="page" value="<?php echo $page ?> ">
if ($page < $counter - 1)
$pagination.= " next »";
else
$pagination.= "<span class=\"disabled\"> next »</span>";
$pagination.= "</div>\n";
Read from your database and populate your table
When you build the form, use something like this to apply the "checked" value of it equals one in the SESSION array
echo "<input type='checkbox' name='cbgroup[]' value='$row[0]'";
if (isset($filtered)) {
$uniqueitemschecked = count($filtered);
for($i=0; $i < $uniqueitemschecked; $i++) {
if ($row[0] == $filtered[$i]) {
echo " checked ";
}
}
}
While you're building the HTML table in the WHILE loop... use this. It will append all the select IDs to a comma separated text value after the loop
...
$allcheckboxids = "";
while ($row = $result->fetch_row()) {
$allcheckboxids = $allcheckboxids.$row[0].",";
...
}
After the loop, write out the hidden text field
echo "<input type='hidden' name='currentids' value='$allcheckboxids'>";

How to fill in placeholder boxes with a foreach loop?

Using PHP (at if it's need, jquery):
I have this page with 30 boxes. It will never be more, or less.
On those 30 boxes, some of them will be filled with "box specific" data.
How can I say:
If there are 20 records on the foreach to loop trought, then, 20 boxes will contain data, and the rest will stay with the placeholders.
If there are 10 records on the foreach, then 20 boxes will stay with the placeholdes.
How can something like this be achieved ?
Can anyone provide me a good example for doing so?
Thanks a lot,
MEM
Assuming $data is a numerically keyed array of your data:
<?php for($i = 0; $i < 30; $i++): ?>
<?php if(isset($data[$i]): ?>
<!-- the html for a box WITH data -->
<?php else: ?>
<!-- html for an empty placeholder box -->
<?php endif; ?>
<?php endfor;?>
Fill an array with the bits of data you do have, add 30 placeholders, take the first 30 elements of the array, and iterate over those.
Do you have names for each box? Assuming there is some name/id in your 10 or 20 records which I'm assuming are in an array...
function OutputBoxes($records, $boxes){
foreach($boxes as $box){
$box->PopulateWithPlaceHolder();
}
foreach($records as $record){
$box = GetMatchingBox($record);
$box->SetValue($record['valueProperty']);
}
foreach($boxes as $box){
echo $box->ElementHtml();
}
}
Assuming here that you have some type of box object which knows how to output itself as HTML, and set whatever value you would like that is coming from the record.
make an array with all your data. then run a for-loop (0..30) to build your boxes. For each item in your loop, if your box-data array contains an element, then output specific data, otherwise output placeholder data. Something like this...
<?php
$box_data = array(
"data for box 1",
"data for box 2",
"data for box 3"
);
for( $i=0; $i<30; ++$i ) {
if( $i >= count($box_data) ) {
// output "placeholder box"
echo "<div class=\"box placeholder\">Placeholder Box</div>";
} else {
// output the box's specific data
echo "<div class=\"box non-placeholder\">{$box_data[$i]}</div>";
}
}

Categories