I have a form with multiple inputs like this:
<div id="users">
<input type="text" name="title[]" required>
<input type="file" name="images[]">
<input type="text" name="title[]" required>
<input type="file" name="images[]">
<input type="text" name="title[]" required>
<input type="file" name="images[]">
</div>
<input type="button" value="add new user">
<input type="submit" value="submit">
the problem is that selecting image is optional and if the user doesn't select any image for any of titles the posted data would be like this:
title = ["title1","title2","title3"]
images = [image1.jpg,image3.jpg]
the count of users is not fixed and user can add any desired number of titles and images by clicking on the add new user button. so "add new user" button will add a pair of these inputs to users div:
<input type="text" name="title[]" required>
<input type="file" name="images[]">
is there any way to detect if the file is selected or not? or to send a default value for not selected file inputs? I want to set null value for image if no file is selected, like this:
user1:{title="title1",image=image1.jpg}
user2:{title="title2",image=null}
user3:{title="title3",image=image3.jpg}
.
.
.
You can check if particular index is set for file:
var_dump($_POST['title'][0]);
if (isset($_FILES['images']['tmp_name'][0])) {
var_dump($_FILES['images']['tmp_name'][0]);
}
All you have to do is process the 2 arrays and check there is a matching image with each title. If there is not a image for each title, put anything that you like in place of the image name
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$output = [];
foreach( $_POST['title'] as $idx => $title){
$u = $idx+1;
$output['user'.$u] = ['title'=>$title,
'images'=> $_POST['images'][$idx] == '' ? 'NULL' : $_POST['images'][$idx]];
}
$j = json_encode($output);
echo $j;
}
RESULT
{
"user1":{"title":"asss","images":"NULL"},
"user2":{"title":"dd","images":"hammer.jpg"}
}
Thank you everybody, Pavol Velky was right partially, Although the array size is less than the number of inputs, but the browser will set an index to the array, in example if you have two inputs and just select the second one, the array will be like : item:[1:{}] (if you select first one: item:[{}]) and you can check the order by the index number.
Related
This is the output of my code
Every item has its own item number. I will be entering randomly a value for 3 items, after doing so I will click on the add button and will be redirected to a confirmation page. How will I get the values with its corresponding item?
Thanks in advance for the answers :)
Use input name as array.
<input type="text" name="price[]" />
<input type="text" name="price[]" />
<input type="text" name="price[]" />
<input type="text" name="price[]" />
<input type="text" name="price[]" />
Get values like this
$price = $_POST['price'];
foreach($price as $key => $val ) {
echo $val;
echo "<br>";
}
You can bind or keep the text box name same as your database row ID so when you submit and in the target page you can redo the select and update the field in the database like
<input type="text" name="$id" />
in the target page use Select Query looping and give
Update table_name set field_name=$_REQUEST[$id] where id=$id
i have a form that allows input of name ,email & photo...when i click on submit i want it to insert a row into the posttype called'contact' with the info submitted the by the form and the image as the featured image but it does nothing
my code
<?php
if (isset($_POST['submit'])) {
$yourname=$_POST['yourname'];
$email=$_POST['email'];
$myimage=$_POST['myimage'];
include_once('../../../wp-config.php');
global $wpdb;
$table = 'wp_posts';
$data = array(
post_title=>$yourname,
post_status=>'Published',
post_type=>'contacts',
email=>$email,
featured_image=>$myimage
);
$wpdb->insert( $table, $data);
}
?>
<form action="" method="POST">
Your Name: <input type="text" name="yourname" value=""> <br>
Your Email: <input type="text" name="email" value=""> <br>
Image: <input type="file" name="myimage" id=""><br>
<input type="submit" name="submit" value="submit" />
</form>
is there any way i can check if row is uploaded & echo a message if insert is done and then redirect to a new url after few seconds.
Check if columns passed on $data exists in database or in form don't have method="post" enctype="multipart/form-data", try insert this.
You can not get the value of uploaded files from the $_POST variable. For that you need to use $_FILES variable.
To make that code work first you have to add following :
In the form tag you need to add method="post" enctype="multipart/form-data".
In the the PHP script where you get the value of image, Use this code to get the value of image.
featured_image => $_FILES['myimage']['name']
Hi I'm quite new to php and I'm currently making a webpage similar to the ones used by supermarkets for stock management control as part of an assignment. I have the following form where the cashier would enter the product Id and the quantity of the item being purchased.
The form will then call another php file named cashsale.php which will take these inputs and update the tables in my database so that levels of stock on shelves in supermarkets are up to date with the new amounts (i.e. older qty - qty entered) and management can be advised when reorder is needed.
As it is the form works well, however I was advised to edit it in a way that a cashier can enter multiple products and quantities before submitting (i.e. the form will sort of show itself again) and allow the user to edit or remove any items before actually submitting the values to cashsale.php to manipulate the tables. I seem to be at a loss as to how this can be done.
I wanted to create a new button named "Add" which would display the form again, i.e. allow the user to check in more items, but I am confused as to how this can be done and also as to how I will be able to update tables then since I would be having more then just 2 inputs.
Can anyone help me on this please? Thanks in advance. The following is my html form:
center form action="cashsale.php" method ="post"
Product ID: <input name= "id" type="int" > <br>
Quantity:<input name="qty" type="int">
<input type="button" name = "Add" onclick="add">
<input type="Submit" name ="Submit" value = "Submit">
form center
I was not allowed to use html tags for form and center so I removed the < >. The following is some of the modifications done in the cashsale.php file just to give a clearer example.
$result = mysql_query("SELECT * FROM shelfingdetails where prodId =' " .$id. " '");
if (!$result){
die (mysql_error());
}
while ($row =mysql_fetch_array($result))
{
$qtyOnShelf= $row ['QtyOnShelf'];
$max=$row['max'];
$newQtyShelf=$qtyOnShelf-$qty;
}
$update=mysql_query("UPDATE shelfingdetails SET QtyOnShelf ='". $newQtyShelf. "' where prodId = '". $id. "';");
I hope someone can help. Thanks!
You just have to pass an array. For this you have to generate the inputs with PHP or javascript (I'm gona use jQuery to keep the code nice and simpe).
If you use PHP:
// PHP
<?php
if(isset($_POST['submit']) && $_POST['submit']){
//save data
} elseif(isset($_POST['Add']) && $_POST['Add']) {
$max = (int)$_POST['max']
} else { $max = 1; }
?>
<form action="" method="post">
<?php
for($i = 0;$i < $max;$i++){
?>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
<?php
}
?>
<input type="hidden" name="max" value="<?= $i; ?>" />
<input type="submit" name="Add" />
<input type="submit" name="Submit" value="Submit" />
</form>
If yo use Javascript:
//HTML
<form action="" method="post" id="form">
<div id="add">
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
</div>
<input type="hidden" name="max" value="<?= $i; ?>" />
<input type="button" name="Add" onclick="addRow();" />
<input type="submit" name="Submit" value="Submit" />
</form>
// jQuery
function addRow(){
$("#add").append("<br />Product ID: <input name='id[]' type='int' >" +
"<br />Quantity: <input name='qty[]' type='int'>");
}
you have to use id[] and qty[] to pass them as an array and with the add button generate as many of them as you need. Like so:
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int"> <br>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int"> <br>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
<input type="button" name = "Add" onclick="add">
Then on the backand use for loop to save all the data.
$max = count($_POST['id']);
$id = $_POST['id'];
$newQtyShelf = $_POST['qty'];
for($i = 0;$i < $max;$i++){
$update=mysql_query("UPDATE shelfingdetails
SET QtyOnShelf ='". (int)$newQtyShelf[i]. "'
WHERE prodId = '". (int)$id[i]. "';");
}
I just wanted to show you the idea, please don't use this specific code, because you should use mysqli instead of mysql and also mysqli_escape_string to make sure that the user not submits incorrect data.
I have a form with various fiedls (Name, email, password, etc..). It also has a set of 5 check-boxes. As i have to update a database i prefer doing server-side validation and i am using php.
If a validation error occurs, the error is displayed on the top of the page along with the form and the previously entered data in the text fields. I am not able to retain the state of the checkboxes and radio buttons. The all revert back to being not selected. What should i do to retain the state of checkboxes and radio buttons?
The form looks something like..:
Password:<input type="text" name="password" size="16" maxlength="9" value="<?php echo $_POST['password']?>"/>
Retype Password:<input type="text" name="repassword" value="<?php echo $_POST['repassword']?>"/>
Select:<br />
<input type="checkbox" name="option1" value="on1" id="opt1"/> <label for="opt1">Option1</label><br />
<input type="checkbox" name="option2" value="on2" id="opt2"/> <label for="opt2">Option2</label><br />
<input type="checkbox" name="option3" value="on3" id="opt3"/> <label for="opt3">Option3</label><br />
<input type="checkbox" name="option4" value="on4" id="opt4"/> <label for="opt4">Option4</label><br />
<input type="checkbox" name="option5" value="on5" id="opt5"/> <label for="opt5">Option5</label><br />
Mobile No:<input type="text" name="mobileno" maxlength="10" value="<?php echo $_POST['mobileno']?>"/>
What you're talking about is Sticky Forms. You can implement sticky forms in many ways, my choice is to use session. If there is an error in your validation, simply dump everything in your POST data into session. On your form page, check to see if the value is set in session and set the default value of the form control it if it is:
Validation Page:
<?php
session_start();
if(/** some error condition **/) {
foreach($_POST as $k => $v)
$_SESSION['sticky_'.$k] = $v;
header('Location: http://site.com/yourform.php');
exit();
}
?>
Form Page:
<?php session_start(); ?>
<input type = "checkbox" name = "option1" value = "on1" id = "opt1" <?php
if(isset($_SESSION['sticky_option1']))
echo('checked = "checked");
?>/>
Example TextBox: <input type = "text" name = "textBoxName" <?php
if(isset($_SESSION['sticky_textBoxName']))
echo('value = "' . $_SESSION['sticky_textBoxName'] . '"');
?>
...
<?php
// Erase the POST values from session after the HTML is constructed.
foreach($_SESSION as $k => $v)
if( strpos($k, 'sticky_' !== false )
unset($_SESSION[$k]);
?>
Add a checked attribute to any checkbox who's value is in the submitted data.
I have a form which has the ability to copy a row of several fields using jquery - my question is how do I access these form values in the target php page?
Any code, by chance? Anyway, you can make it add a name to the new field with square braces, so ti will be accessed as an array, like it happens with multiselect checkboxes
es: new field 1 <input type="text" name="added[]" value="">
new field 2 <input type="text" name="added[]" value="">
and so on...
Then you have everythin in the $_POST['added'] array
If they have the same 'name' attribute value, change that value to 'name[]' so that they look like
<input type="text" name="name[]" />
<input type="text" name="name[]" />
<input type="text" name="name[]" />
<input type="text" name="name[]" />
//etc...
and you should be able to access them by using:
$value = $_POST['name'][0];
where 0 is the index of the field, IE, the first field is 0, second is 1...
It is easier to access these using a for loop
for($i = 0; $i < count($_POST['name']; $i++)
// actions with $_POST['name'][$i]
or a foreach loop.
foreach($_POST['name'] as $value)
// actions with $value
Depends on how jquery is adding them. Do the following on the called page and see how they're being passed through.
var_dump( $_POST ); // Or maybe $_GET