I have a form that records various fields with a variable name in autoincrement.
when I save my my form variables looks like
<form>
<?php
$i = 1;
foreach ($variables as $var ) {
echo '<input type="text" name="txt$i" value="$var->name" />';
$i ++;
}
?>
</form>
And my question is how to display the value of the input field, i make that, but not working
<?php
foreach ($variables as $var) {
echo $var->txt$i;
$i ++;
}
?>
There are couple of bugs in both of your scripts. Here they are fixed.
<form>
<?php
$i = 1;
foreach ($variables as $var ) {
echo '<input type="text" name="txt' . $i . '" value="' . $var->name . '" />';
$i++;
}
?>
</form>
<?php
$i = 1;
foreach ($variables as $var) {
echo $var->{"txt" . $i};
$i++;
}
?>
In PHP, single-quoted strings do not allow for variable interpolation.
Try:
echo '<input type="text" name="txt' . $i . '" value="' . $var->name . '" />';
This is happening because you are using single quotes:
echo '<input type="text" name="txt$i" value="$var->name" />';
and inside single quotes variable interpolation does not happen.
Instead use:
echo '<input type="text" name="txt'.$i.'" value="'.$var->name.'" />';
This should work,
<form>
<?php
$variables = array("red","yellow","blue","orange","green");
$i = 1;
foreach ($variables as $var ) {
$name = "txt".$i;
echo "<input type='text' name='".$name."' value='".$var."' />";
$i++;
} ?>
</form>
You need to put variables in double quotes, i thought it would be easier to create a name variable and concatenate the incremented value on to the end of it
Can't get what you want from your question.
May be just
echo $txt.$i;
?
Related
My main question is why is PDO::exec not executing every iteration of my loop, and instead only executing in the first iteration.
I am trying to insert coordinates into my MySQL database.
My database structure is (number(primary key), x, y, z).
I ask the user to insert a number ($n), and then ask them to fill in $n sets of coordinates.
The users inputs are passed to another page with $_POST, then retrieved by dynamic variable names and inserted into the database.
Everything works, except the loop only writes to the database its first iteration. So I end up with results for x1,z1,y1 but nothing else.
Can anyone explain what I am doing wrong (other than not using arrays)?
<?php
require_once('db.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
${'x' . $i} = $_POST["x" . $i];
${'y' . $i} = $_POST["y" . $i];
${'z' . $i} = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '${'x' . $i}', '${'y' . $i}', '${'z' . $i}')");
}
?>
Here is my form
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
require_once('aaron_stockdale_database.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
$x = $_POST["x" . $i];
$y = $_POST["y" . $i];
$z = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '$x', '$y', '$z')");
}
the rest is on you ;)
And also check if any of the fields a primary key, that will prevent insert it twice.
Since you have received an acceptable answer for your question, I'd like to give you a hint on your html code.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
Now, this code can be cleaned up a bit.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
echo 'x' . $i+1 . '<input name="x' . $i+1 . '" type=text>, y' . $i+1 . ' <input name="y' . $i+1. '" type=text>, z' . $i+1 . '<input name="z' . $i+1 . '" type=text><br>'
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" value="Submit">
</form>
I changed the "oonClick" to "onClick", and then afterwards I removed it, as when you submit, you don't need to navigate, as the browser will do this, upon submission.
And then I removed the repetitive opening and closing of php tags, and combined all the echos into one.
Here's my solution in one file:
<!DOCTYPE html>
<html lang=en>
<head>
<script>
function validcoord(e) {
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
return true;
// Numeral Characters
else if ((("0123456789-.,").indexOf(keychar) > -1))
return true;
else
return false;
}
</script>
<style>
input[type="number"] { text-align: right; width: 50px; }
label { margin-left: 4em; }
</style>
</head>
<body>
<?php
define ("SELF", $_SERVER['PHP_SELF']);
define ("EOL", "\r\n");
// Modify as needed
define ("MINNUMCORDS" , "1");
define ("MAXNUMCORDS" , "10");
define ("DFLTNUMCORDS", "2");
$formSubmitted = (empty($_POST)) ? FALSE : TRUE;
if (!$formSubmitted) {
$htmlOutput = '
<form action="' . SELF . '" method=post name=foo id=foo>
<input type=hidden name=current value=0>
<label>Enter the number of Coordinates:
<input type=number autofocus onFocus="this.select()"' .
' min=' . MINNUMCORDS .
' max=' . MAXNUMCORDS .
' value=' . DFLTNUMCORDS .
' name=numcords /></label>
</form>' . EOL;
echo $htmlOutput;
} // end if not submitted
else { // a form HAS been submitted
foreach ($_POST as $key => $value) { $$key = $value; }
unset($_POST);
if (!empty($coord)) { // We got some input that may be a valid x,y,z coordinate
if ( substr_count($coord, ",") != 2 ) {
$error = "We're looking for THREE numbers seperated by TWO commas.";
} // end if we don't have three values
else { // We got three Values
$coord = trim($coord);
list($x,$y,$z) = explode(",", $coord);
if ( !(is_numeric($x) && is_numeric($y) && is_numeric($z)) ) {
$error = "We're looking for three VALID NUMBERS seperated by two commas.";
} // end if all three numbers are not valid
else { // We got three Values and each of them are numbers
require('db.php');
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$numcords', '$x', '$y', '$z')");
//echo "INSERT INTO coordinate3d (number,x,y,z) VALUES ('$numcords', '$x', '$y', '$z')<br />" . EOL;
} // end three valid numbers
} // end three values
} // end if we have some input in $coord
if ($error) {
echo "~~ " . $error . "<br /><br />" . EOL;
--$current;
} // end if error
if ( $current < $numcords ) {
$htmlOutput = 'Please enter the coordinate in the form: x,y,z (Ex: -.4,2,8.5)' . EOL;
$htmlOutput .= '<form action="' . SELF . '" method=post name=bar id=bar>' . EOL;
$htmlOutput .= ' <input type=hidden name=numcords value="' . $numcords . '" />' . EOL;
$htmlOutput .= ' <input type=hidden name=current value="' . ++$current . '" />' . EOL;
$htmlOutput .= ' <label>Coord #' . $current . ': ';
$htmlOutput .= '<input type=text name=coord size=12 maxlength=48 ' .
'autofocus onKeyPress="return validcoord(event);" /></label>' . EOL;
$htmlOutput .= '</form>' . EOL;
echo $htmlOutput;
} // end if we need to get another coord
} // end form was submitted
?>
</body>
</html>
I have created a for loop that generates a form div repeatedly:
for ($i = 1; $i <= $noOfTanks; $i++) {
echo '<div class="';
echo $col;
echo '"><img id="tank" src="img/tank.svg" alt="Tank"></br>
<label for="tankName';
echo $i;
echo '">Tank Name ';
echo $i;
echo '</label>
<input type="text" id="tankName';
echo $i;
echo '" name="tankName';
echo $i;
echo '"></br>
<label class="rightT" for="tankVolume';
echo $i;
echo '">Tank Volume ';
echo $i;
echo '</label>
<input class="rightT" type="text" id="tankVolume';
echo $i;
echo '" name="tankVolume';
echo $i;
echo '"><p>L</p>
</div>';}
The code generated a number of inputs. I want to gather all this input values into two arrays tankName[], tankVolume[]. I am struggling to understand how to use $_POST to do this.
Thanks for any help.
Use array of inputs.
Example:
<input class="rightT" type="text" id="tankVolume1" name="tankVolume[]"/>
I can't figure out why my values aren't being passed from the form. I can't spot an error.
The Form Code:
$table = $_POST['table'];
$id = $_POST['id'];
$count = 0;
$query = "SELECT * FROM `" . $table . "` WHERE id = " . $id;
$result1 = mysqli_query($link, $query);
echo '<center><table style="text-align:center">';
echo '<form action="edit-process.php" method="post">';
while($row = mysqli_fetch_assoc($result1)){
foreach($row as $key => $val){
if ($count > 0){
echo "<tr>";
echo "<td>" . $key . "</td>";
echo '<td><input type="text" name="' . $key . '" value="' . $val . '"></td>';
echo "</tr>";
$count++;
}
else $count++;
}
}
echo '<input type="hidden" name="table" value="' . $table . '" />';
echo '<input type="hidden" name="id" value="' . $id . '" />';
echo '<tr><td><input type="submit" value="Save Changes" /></td></tr>';
echo "</form>";
echo "</table>";
The php file:
$table = $_POST['table'];
$id = $_POST['id'];
$count1 = 0;
$count2 = 0;
$result = mysqli_query($link, "SHOW COLUMNS FROM `" . $table . "`");
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$keyNames[$count2] = $row['Field'];
$count2++;
}
}
while ($count1 < $count2){
if ($count1 > 0) {
$value = mysqli_real_escape_string($_POST[$keyNames[$count1]]);
$query2 = "UPDATE `" . $table . "` SET `" . $keyNames[$count1] . "` = '" . $value . "' WHERE id = " . $id;
echo $query2 . "<br>";
$result2 = mysqli_query($link, $query2);
$count1++;
}
else $count1++;
}
I am avoiding displaying the id column with all the counts. The output of the echo-ed queries are:
Any ideas?
EDIT
I'll take care of changing everything over to procedural style once I figure out this issue. If I get rid of the mysqli_real_escape_string, it passes all the data except those columns with spaces in them. I thought that's what backticks were for? Is there something else I can do to make the columns with two words pass data like those with one word?
You need to switch these rows -
echo '<center><table style="text-align:center">';
echo '<form action="edit-process.php" method="post">';
....
echo "</form>";
echo "</table>";
to
echo '<form action="edit-process.php" method="post">';
echo '<center><table style="text-align:center">';
....
echo "</table>";
echo "</form>";
Having the <form> inside the <table> is invalid code. It either needs to wrap the <table> or be inside <td></td>.
see also -
form inside table
Form inside a table
Update #1-
On your Edit
Spaces in <input name=""> will be replaced with _ so your $_POST[] name will not match your <input name="">. from the manual - http://www.php.net/manual/en/language.variables.external.php
Note:
Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].
see also -
Can <input> elements have capital letters and spaces in PHP
I am creating a form based on a user selection of $node_number ... so the form looks like:
function createForm($node_number) {
echo "<form id=\"form\" name=\"form\" action=\"molecule_display.php\" method=\"post\">";
for ($n = 1; $n <= $node_number; $n++) {
echo "<fieldset class=\"step\">
<input id=\"node_title" . $n . "\" name=\"node_title" . $n . "\" />
<input id=\"node_comment" . $n . "\" name=\"node_comment" . $n . "\" type=\"textarea\" />
</fieldset>";
}
echo "<input type=\"hidden\" name=\"node_number\" value=\"" . $node_number . "\">
<button id=\"submit_node\" type=\"submit\">Submit</button>"
echo "</form>";
}
Which will create $node_number of versions of that form element. My question is how to dynamically name the form elements to be able to manage them easier when I am processing them. The way I'm doing it right now, by adding the $n iterator to the name attribute is not ideal I think.
I understand that I can declare the name="" attribute as an array like name[]="" ... in terms of giving each sub-element of the larger form a unique name.
I'm guessing I want a multi-dimensional array of the individual form segment ... just not sure how to best handle those within a form and within the $_POST variable.
Does anyone have any suggestions?
I think you can do it this way:
function createForm($node_number) {
echo '<form id="form" name="form" action="molecule_display.php" method="post">';
for ($n = 1; $n <= $node_number; $n++) {
echo '<fieldset class="step">
<input id="node_title'.$n.'" name="nodes['.$n.'][node_title]" />
<input id="node_comment'.$n.'" name="nodes['.$n.'][node_comment]" type="textarea" />
<button id="submit_node" type="submit">Submit</button></p>
</fieldset>';
}
echo '</form>';
}
And then get $_POST['nodes'] which will be multidimensional array, which you can iterate with foreach. You will get $_POST['nodes'][1] = array('node_title'=>... , 'node_comment'=>...); and so on.
If you use the array like you were saying in your post you should be able to access them pretty easily.
function createForm($node_number) {
echo "<form id=\"form\" name=\"form\" action=\"molecule_display.php\" method=\"post\">";
for ($n = 1; $n <= $node_number; $n++) {
echo "<fieldset class=\"step\">
<input id=\"node_title_" . $n . "\" name=\"node_title[" . $n . "]\" />
<input id=\"node_comment_" . $n . "\" name=\"node_comment[" . $n . "]\" type=\"textarea\" />
<button name=\"submit_node[" . $n . "]\" type=\"submit\">Submit</button></p>
</fieldset>";
}
echo "</form>";
}
I also changed the submit_node to a name and gave it an array value because an ID must be unique, which will cause errors if you are referencing it somewhere.
You could loop through the results like this:
foreach ($_POST['node_title'] as $key => $response) {
$title = $response;
$comment = (!empty($_POST['node_comment'][$key])) ? $_POST['node_comment'][$key] : "";
// Save title / comment here.
}
Since every form has its own submit button, nothing stops you from using name="node_title" in all of them. If you now add <input type="hidden" name="index" value="$n"> and read this first, your logic becomes very easy.
Given the code below when I select a value from my dropdown box [S, M, L] and hit submit I get one of the following outputs:
S is equal to
M is equal to
L is equal to
I would like the output to be along the lines of
S is equal to Small
M is equal to Medium
L is equal to Large
Can something be added to my code to accomplish this? Or do I need to take a different approach?
<form action="?" method="post">
<?php
$size = array();
$size[] = "";
$size[] = "S";
$size[] = "M";
$size[] = "L";
if(isset($_REQUEST['list'])){
echo $size[(int)$_REQUEST['list']]." is equal to "."<br />";
}
echo '<select name="list">'."\n";
$count = 0;
foreach($size as $size){
echo '<option value="'.$count.'">'.$size.'</option>'."\n";
$count++;
}
echo '</select>';
?>
<input type="submit" value="submit" />
</form>
<form action="?" method="post">
Why not use an associative array and then you don't have to mess around with ints or $counts?
<form action="?" method="post">
<?php
$sizes = array(
"S" => "Small",
"M" => "Medium",
"L" => "Large"
);
if(isset($_REQUEST['list'])){
echo "<p>" . $_REQUEST['list'] . " is equal to " . $sizes[$_REQUEST['list']] . "</p>";
}
?>
<select name="list">
<option value="">Choose one</option>
<?php
foreach($sizes as $key => $val){
echo "<option value='$key'>$key - $val</option>\n";
}
?>
</select>
<input type="submit" value="submit" />
</form>
The output will look something like this:
S is equal to Small
+------------+-+
| Choose one |▼|
+------------+-+
| S - Small |
| M - Medium |
| L - Large |
+--------------+
With this solution you can reuse the original static array to populate the post echo. Also try to avoid using \n in your html instead use the semantic <br>.
<form action="?" method="post">
<?php
$size = array(""=>"","Small"=>"S","Medium"=>"M","Large"=>"L");
if(isset($_REQUEST['list'])){
echo $size[$_REQUEST['list']]." is equal to ".$_REQUEST['list']."<br />";
}
echo "<select name='list'>";
foreach($size as $key=>$value){
echo "<option value='$key'>$value</option>";
}
echo '</select>';
?>
<input type="submit" value="submit" />
</form>
You need to make the array $sizes, then foreach ($sizes as $size) for your loop. THen in the echo you need this:
if(isset($_REQUEST['list'])){
switch($size[$_REQUEST['list']])
{
case "S":
$size = "Small";
break;
case "M":
$size = "Medium";
break;
case "L":
$size = "Large";
break;
}
echo $size[(int)$_REQUEST['list']] . " is equal to " . " . $size . "<br />";
}
But really you would be far better using the letters as keys for the array, and the sizes as the values: $sizes['S'] = "Small" then it would be simply in your loop
foreach ($sizes as $key => $size)
{
echo "<option value='" . $key . "'>" . $size . "</option>";
}
and to display:
$_REQUEST['list'] . " is equal to " . " . $sizes['$_REQUEST['list']] . "<br />";
You can get your desired result from rewriting your code using nested arrays for your size array like:
$size = array();
$size[] = "";
$size[] = array("S", "Small");
$size[] = array("M", "Medium");
$size[] = array("L", "Large");
if(isset($_REQUEST['list'])){
echo $size[(int)$_REQUEST['list']][0]." is equal to ". $size[(int)$_REQUEST['list']][1] ."<br />";
}
echo '<select name="list">'."\n";
$count = 0;
foreach($size as $size){
echo '<option value="'.$count.'">'.$size[0].'</option>'."\n";
$count++;
}
echo '</select>';
?>
<input type="submit" value="submit" />
</form>
Im not sure I get your problem right
But why not set the value to Small, Medium & Large while you keep the output S, M, L if you want that.
Then S = Small.