I got this 2 array in a form to be process. However, i only manage to get the output from only one of the array. Sample as below :
<inputs id="location" type="text" name="data[]" value=""/>
<input id="shipval" type="text" name="data[][id]" value=""/>
And in the PHP part is below :
foreach ($_POST ["data"] as $id => $subs) {
foreach ($subs as $key=>$sub) {
$subcategory = $sub;
if($subs['id']=="$subcategory"){
echo $sql = " insert into x(kodLebuhraya,kodSeksyen) values ('".$subs['id']."','".$sub."')";echo "<br>";
}else{
//echo "hi2";
echo $sql = " insert into x(kodLebuhraya,kodSeksyen) values ('".$subs['id']."','".$sub."')";echo "<br>";
}
}
}
It means one location for one shipval. i have multiple input field for location and shipval. Can you guys enlight me which one is wrong. Thanks in advanced.
So basically you need to pass location and shipval in pairs.
Try this structure in HTML:
<label>Set One</label>
<input class="location" type="text" name="data[location][]" value=""/>
<input class="shipval" type="text" name="data[shipval][]" value=""/>
<label>Set Two</label>
<input class="location" type="text" name="data[location][]" value=""/>
<input class="shipval" type="text" name="data[shipval][]" value=""/>
<label>Set Three</label>
<input class="location" type="text" name="data[location][]" value=""/>
<input class="shipval" type="text" name="data[shipval][]" value=""/>
And this code for PHP:
foreach ($_POST['data']['location'] as $key => $location) {
$shipVal = $_POST['data']['shipval'][$key];
//now you have a pair of $location and $shipVal
echo $location.' : '.$shipVal.'<hr>';
}
Avoid using named indexes after unnamed ones ex. <input name="array[][named]" /> you can lose order of fields if one of pair fields is empty.
You have <inputs id="location" instead of <input id="location"
Also... foreach ($subs as $key => $sub) { will throw an error for <inputs id="location" type="text" name="data[]" value=""/> because it is not multidimensional. So try changing that to <inputs id="location" type="text" name="data[][]" value=""/>
For multiple select, the name has to end in square brackets, so you'll need to change the name of your shipval inputs
Firstly you have writtten inputs instead of input.
Secondly, this line:
foreach ($subs as $key=>$sub) {
will treat each variable as an array, but the location isn't an array.
I did not see the need for a loop since you want to just access $_POST['data'][0] and $_POST['data'][1]['id']
I also noticed that your SQL is a duplicate so you can try You can try
$sql = "INSERT INTO x(`kodLebuhraya`,`kodSeksyen`) VALUES ('%s','%s')" ;
printf($sql,mysqli_real_escape_string($_POST['data'][0]),mysqli_real_escape_string($_POST['data'][1]['id']));
Output
INSERT INTO x(`kodLebuhraya`,`kodSeksyen`) VALUES ('A','B')
Form Used
<form method="POST">
A : <input id="location" type="text" name="data[]" value="" />
B : <input id="shipval" type="text" name="data[][id]" value="" />
<input id="shipval" type="submit" name="submit" value="Submit" />
</form>
Related
I need to create a table of 17 rows where each row contains information such as row number, name, surname, email and birthday. The data is provided by this form:
<form action="index.php" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
After clicking submit the data should be displayed in the nth row of the table(row number one if it is the first "pack" of data submitted, number two if its the second and so on). This problem could easely be solved using databases but i cannot use them(by professors order).
I tried to create an array than push values into it like this:
$array_name = array();
$name = $_POST["name"];
array_push($array_name, $name);
This approach doesn't work(the index of the array stays 0 alla of the time so it keeps replacing the first value again and again) and manually incrementing the index counter of the array doesn't work either.
Normally one should use a database approach but your professor explicitly forbids it.
There are many other ways to do it. (store as TEXT/JSON/CSV file or localstorage / cookies), etc. For me I would use session to do the job
declare a session variable which is an array
if user submits the form, store the POST data into another array (subarray) containing name, surname, birthday, email
add the subarray into the main session variable array
print it out at the end as a table
So the PHP will be:
<?php
session_start();
?>
<form action="#" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="email" placeholder="email" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
<?php
if (!isset($_SESSION["arr"])){
$_SESSION["arr"]=array();
}
if ($_POST) {
$subarray=array(
"name"=>$_POST["name"],
"surname"=>$_POST["surname"],
"birthday"=>$_POST["birthday"],
"email"=>$_POST["email"]
);
$_SESSION["arr"][]=$subarray;
}
echo "<table border=1><tr><td>Name<td>Surname<td>Email<td>Birthday";
foreach($_SESSION["arr"] as $suba){
echo "<tr><td>" . $suba["name"] ;
echo "<td>" . $suba["surname"] ;
echo "<td>" . $suba["email"] ;
echo "<td>" . $suba["birthday"] ;
}
echo "</table>";
?>
However, if you need the data to be persistent (even after the user closes the browser), then you need to store the data say in file format or cookies, etc.
If you need to save data persistent and using file to save data is acceptable, i'd use something like that:
<?php
$file = 'path/to/file.txt';
$data = json_decode(file_get_contents($file), true);
if ($_POST) {
$data[] = [
"name" => $_POST['name'],
"surname" => $_POST['surname'],
"emailbirthday" => $_POST['emailbirthday'],
"birthday" => $_POST['birthday']
];
}
file_put_contents($file, json_encode($data));
?>
<form action="index.php" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
<table>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Emailbirthday</th>
<th>Birthday</th>
</tr>
<?php
foreach ($data as $row) {
print '<tr>
<td>'.$row['name'].'</td>
<td>'.$row['surname'].'</td>
<td>'.$row['emailbirthday'].'</td>
<td>'.$row['birthday'].'</td>
</tr>';
}
?>
</table>
You can use the post values of hidden fields:
<form action="" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
<?php
if($_POST["names"] == "")
{
$value = $_POST["name"];
}
else
{
$value = $_POST["names"]."-".$_POST["name"];
}
?>
<input type="text" name="names" style='display:none;' value="<?php echo $value ?>">
</form>
I have multiple input fields with the same name. How do I print these fields with foreach?
<!-- One Child -->
<input type="text" name="child_name[]">
<input type="text" name="child_date[1]">
<input type="text" name="child_date[1]">
<input type="text" name="child_date[1]">
<!-- Two Child -->
<input type="text" name="child_name[]">
<input type="text" name="child_date[2]">
<input type="text" name="child_date[2]">
<input type="text" name="child_date[2]">
if you used an input array on the form, instead of manually populating the input names with a number concatenated. Example:-
<input type="text" name="fieldname[]" />
<input type="text" name="fieldname[]" />
<input type="text" name="fieldname[]" />
On the PHP side, simply loop over them:-
$fieldname = $_POST['fieldname'];
foreach($fieldname as $index => $a_name){
$output.= $index . ': '.$a_name . "\n";
}
Sorry for grammar mistakes. I have multiple dynamically created text fields (more than 100). how can i get the values of these fields. i don't know the number of fields. Please help me.
Example
<input type="text" name="id_1" />
<input type="text" name="id_2" />
<input type="text" name="id_3" />
................
<input type="text" name="id_100" />
Use arrays:
<input type="text" name="id[1]" />
<input type="text" name="id[2]" />
<input type="text" name="id[3]" />
Then:
foreach($_POST['id'] as $key => $value) {
echo "text $key = $value";
}
If you mean you want to get their values in PHP easily, just name them like "name[]".
<form method="post" action="yourscript.php">
<input type="text" name="input[]" />
<input type="text" name="input[]" />
<input type="text" name="input[]" />
<input type="text" name="input[]" />
<input type="text" name="input[]" />
<input type="submit" value="Submit" />
</form>
This way you'll be able to get the values in yourscript.php. They'll be in $_POST['input']. Just loop over it using foreach to get the values:
foreach($_POST['input'] as $value) {
// do what you want with the $value
}
Having index numbers in the names like this:
<input type="text" name="input[1]" />
<input type="text" name="input[2]" />
is redundant.
In HTML forms, using jQuery:
$(function() {
$("input[name^='id']").each(function() {
var name = $(this).attr('name');
var inputValue = this.value;
console.log(name + " : "+ this.value);
});
});
Hoa about adding a hidden field to pass the number of fields to the processing script?
<input type='hidden' name='num_text_fields' valus='100>
The do a for loop to get the values
$num_text_fields = $_POST['num_text_fields'];
for ($i=1;$i<=$num_text_fields;$i++)
{
$text_field_name = "id_" . $i;
$value = $_POST[$text_field_name];
// do something with $valus
}
I think the best way to do it is to add a class element to your input.
Then you can be easily able to find them regardless of how many you have
I am in a fix here. I have code that does not insert multiple data into mysql table with one form. Here's my code-
<?php
if (isset($_POST['submitted'])) {
include('config.php');
foreach($_POST['name'] as $row=>$nam) {
$name=$nam;
$class=$_POST['class'][$row];
echo "<br/>" . $name . "<br/>" . $class;
$sql="INSERT INTO multiple (name, class) VALUES ('$name','$class')";
}
if (!mysql_query($sql)) die('Error: ' . mysql_error());
echo "1 record added";
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label>Name1:
<input id="name" name="name[]" type="text">
<input type="hidden" name="submitted" value="true" />
</label>
<label> Class1:
<input id="class" name="class[]" type="text">
</label>
<label>Name2:
<input id="name" name="name[]" type="text">
</label>
<label>Class2:
<input id="class" name="class[]" type="text">
</label>
<label>Name3:
<input id="name" name="name[]" type="text">
</label>
<label>Class3:
<input id="class" name="class[]" type="text">
</label>
<label>Name4:
<input id="name" name="name[]" type="text">
</label>
<label>Class4:
<input id="class" name="class[]" type="text">
</label>
<label>Name5:
<input id="name" name="name[]" type="text">
</label>
<label>Class5:
<input id="class" name="class[]" type="text">
</label>
<input value="Add" type="submit">
</form>
When I press the submit button nothing inserts in the mysql table. Only empty fields are created. If I insert 5 text field I get 5 empty fields in sql table.
Imroz, your use of [] as part of the names of your input elements (not id's) example name="class[]" when the form is posted it builds an array. The post object PHP would recognize would be $_POST['class']
But that being an array means you have to handle it slightly different before inserting it into your database as you can't just (well maybe you can) drop an array into the DB
if you did
for($x=0;$x < count($_POST['class']); $x++)
{
echo $_POST['class'][$x].'<br>';
}
you would be able to see all your posted inputs from the inputs with the name class[]
of course this is a core example of what you need to do overall, but I am just trying to express whats going on with your posted data.
i think your inserting query is problem.....try like this
$query = mysql_query("INSERT INTO category VALUES('','$name','$class','')") or die(mysql_error());
You have the } in the wrong place.
The } right after the $sql= should be moved after the echo "1 record added";
I reformatting your code to use proper indenting and the error was obvious.
I've got a system where I allow a user to select multiple checkboxes from n amount of checkboxes, but also want two more inputs associated with each checkbox. This is for a message, a date and a time. When I post the data to be processed by a PHP script, I'd like to be able to access each of the sets of checkbox and two other inputs so I can see what date and time a user has filled in for each of the messages they've selected. I'm having trouble coming up with a method to associate the two other inputs with each checkbox.
Any ideas how to do this?
You can use arrays in your html inputs like so...
<input type="text" name="messages[1][message]" value="herp" />
<input type="text" name="messages[1][date]" value="24th April" />
<input type="text" name="messages[1][time]" value="13:00" />
<input type="text" name="messages[2][message]" value="derp" />
<input type="text" name="messages[2][date]" value="26th April" />
<input type="text" name="messages[2][time]" value="18:00" />
<?php
$messages = $_REQUEST['messages'];
foreach ($messages as $messageId => $value){
echo $value['message'];
echo $value['date'];
echo $value['time'];
}
Your HTML:
<input type="checkbox" name="car" />
<input type="text" name="msg_car" value="Car message" />
<input type="text" name="date_car" value="Car date" />
<input type="checkbox" name="bike" />
<input type="text" name="msg_bike" value="Bike message" />
<input type="text" name="date_bike" value="Bike date" />
<input type="checkbox" name="train" />
<input type="text" name="msg_train" value="Train message" />
<input type="text" name="date_train" value="Train date" />
<input type="checkbox" name="plane" />
<input type="text" name="msg_plane" value="Plane message" />
<input type="text" name="date_plane" value="Plane date" />
Your PHP script:
$array = array("car", "bike", "train", "plane");
for ($i = 0; $i < count($array); $i++) {
if (isset($_POST[$array[$i]])) {
//Checkbox was checked, get values
$msg = "";
$date = "";
$msg_id = "msg_" . $array[$i];
$date_id = "date_" . $array[$i];
if (isset($_POST[$msg_id]))
$msg = $_POST[$msg_id];
if (isset($_POST[$date_id]))
$date = $_POST[$date_id];
}
}
I think something like this should work. I didn't test it.. So forgive me if this example still contains some minor errors.