i have 5 textboxes with the name of textbox1,textbox2 ... textbox5. now what i want is that instead of putting each of their value in a variable individually I want to do it in a loop, i have my code here but after i enter submit errors like
Array to string conversion in ...
and
Undefined index: textboxArray in...
.please see what's wrong with my code.
if(isset($_POST['submit'])){
for($i=0; $i<5; $i++){
$sasa = $_POST["textbox".[$i].""];
$sql="INSERT into sasa (sasa) values('$sasa')";
$q=$conn->query($sql);
}
}
This is incorrect:
$sasa = $_POST["textbox".[$i].""];
^^^^
[$i] defines a new array with a single integer in it, which you then concatenate into a string. Arrays used in a string context simply become the literal word Array, which means you're effectively running this:
$sasa = $_POST["textboxArray"];
which doesn't exist in your form.
You want
$sasa = $_POST["textbox{$i}"];
instead. Note the {}.
And note that your code is vulnerable to sql injection attacks.
The problem is this line: $sasa = $_POST["textbox".[$i].""];
You should do it as follows:
if(isset($_POST['submit'])){
if(is_array($_POST["textbox"])){
foreach($_POST["textbox"] as $sasa){
//This is unsafe, use prepared statements instead
$sql="INSERT into sasa (sasa) values('$sasa')";
$q=$conn->query($sql);
}
}
}
This allows you to write your form like:
<form method="post" ... >
<input type="text" name="textbox[]"/>
<input type="text" name="textbox[]"/>
<input type="text" name="textbox[]"/>
<button type="submit">Submit</button>
</form>
In answer to your comment, this is how you could add/remove inputs dinamically using jQuery:
var control = $('<div class="controls"></div>');
control.append("<input class='form-control' type='text' name='textbox[]' placeholder='textbox'/><a href='#' class='remove_this btn btn-danger'>remove</a>");
control.appendTo('form');
control.find('.remove_this').click(function(){
control.remove();
});
Related
Started learning PHP today so forgive me for being a noob. I have a simple HTML form where the user inputs 4 strings and then submits.
HTML form
<html>
<head>
<title>EMS</title>
</head>
<body>
<h1>EMS - Add New Employees</h1>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<table>
<tr><td>Enter a NAME:</td><td> <input type="text" name="name"></td></tr>
<tr><td>Enter a PPSN:</td><td> <input type="text" name="ppsn"></td></tr>
<tr><td>Enter a PIN :</td><td> <input type="text" name="pin"></td></tr>
<tr><td>Enter a DOB:</td><td> <input type="text" name="dob"></td></tr>
<tr><td></td><td><input type="submit" value="Add New Employee" name="data_submitted"></td></tr>
</table>
</form>
</html>
I want to implode the 4 elements in the $_POST["data submitted"] array to a string.
PHP
<?php
if (isset($_POST['data_submitted'])){
$employee = implode(",",$_POST['data_submitted']);
echo "employee = ".$employee;
}
?>
Why is it that when I run the project, Input the 4 strings into the form and submit that there is nothing contained within the employee string when its outputed? There is however a value in the employee string when I just implode the $_POST array like so without 'data_submitted'.
$employee = implode(",",$_POST);
The output of the $employee string is now - employee = will,03044,0303,27/5/6,Add New Employee
It contains the name,pps,pin,dob and this ADD New Employee value?
How do I just get the $employee string to contain just the name,pps,pin and dob from the $POST_[data_submitted] array?
If you wish to implode the submitted data, then you need to refer to the specific items, as follows:
<?php
$clean = [];
if (isset($_POST['data_submitted'])){
// one way to deal with possibly tainted data
$clean['name'] = htmlentities($_POST['name']);
$clean['ppsn'] = htmlentities($_POST['ppsn']);
$clean['pin'] = htmlentities($_POST['pin']);
$clean['dob'] = htmlentites($_POST['dob']);
$employee = implode(",",$clean);
echo "employee = $employee";
}
Never use submitted data without first checking to make sure that it is safe to do so. You need to validate it. Since the OP doesn't specify what kind of data the named inputs "ppsn", "pin", "dob" pertain to, this example does a minimum of validation. Each input might require more or something different.
Whether you're new or familiar with PHP, it is a good idea to frequently read the online Manual.
First, you need to know that php will treat value in the format: value="value here" as string.
So, calling implode(",",$_POST['data_submitted']); will return Add New Employee as declared here: <input type="submit" value="Add New Employee" name="data_submitted">.
From your question:
How do I just get the $employee string to contain just the name, pps, pin and dob from the $_POST[data_submitted] array?
Solution
1. Unset the <code>$_POST['data_submitted']</code> index in the $_POST super global variable
2. Implode it
// Unset the $_POST['data_submitted'] index
$post_data = unset( $_POST['data_submitted'] );
// Format the post data now
$format_post_data = implode( ",", $post_data );
// Escape and display the formatted data
echo htmlentities( $format_post_data, ENT_QUOTES );
I have to put 2 id-s together from $_POST then I want to explode them, example:
My id-s are 38 and 310. I made the id-s to this id = "38.310" in my html file.
After $_POST I want to explode the id-s:
$id=$_POST['id'];
echo($id); // Gives 38.31
$new_id = explode(".", $id);
echo($new_id[0]); // Gives 38
echo($new_id[1]); // Gives 31
Is the a way to get these id-s not rounded?
I need the 38 and the 310! The id 310 can be also 1003000 ...
EDIT:
function dostuff(document, message, id, action) {
var eingabe;
eingabe = confirm(message);
if (eingabe === true) {
document.msgform.action.value = action;
document.msgform.id.value = id;
document.msgform.submit();
} else {
return true;
}
return false;
}
LINK
<a href="#" onclick="dostuff(document, 'MESSAGE',<?php echo($row['vID']);?>.<?php echo($row['id']);?>,'FITTER_fitter_repaired');" class="button small red" >ACTION</a>
$row['vID'] = 38
$row['ID'] = 310
and my submit looks like this
<form enctype="multipart/form-data" name="msgform" action="" method="post">
<input type="hidden" value="" name="action"/>
<input type="hidden" value="" name="id"/>
</form>
Not 100% sure why your doing that, but why not just use a POST array like
id[]=38&id[]=310
is the a way to get these ids not rounded?
There are a few ways, I prefer to cast it to an integer:
$id = (int)$_POST['id'];
Others ways would be intval() or floor().
I don't know what the function dostuff is doing, but Javascript is the evil one. Put quotes around the values. In this way there is no casting involved and it gets posted as string.
<a href="#"
onclick="dostuff(document, 'MESSAGE', '<?php echo($row['vID']);?>.<?php echo($row['id']);?>','FITTER_fitter_repaired');" class="button small red" >ACTION</a>
^ ^
EDIT:
But I also think that Lee's solution would be better. Just make 2 input fields and fill them in your dostuff function. You could also give id's to the input fields to make it easier to fill.
<input id="id1" type="hidden" value="" name="id[]"/>
<input id="id2" type="hidden" value="" name="id[]"/>
Alternatively, if you dont understand #Lee answer you could use something other than a . as the seperator so PHP does not assume the variable is a number.
Best not use a coma either as that is the decimal in some countries.
So for example use the dollar sign `id="38$310"
and $new_id = explode("$", $id);
I am doing a project in which as per number getting by GET method, I display dynamic number of HTML Textbox for storing Multiple values. I am giving each textbox unique name+id in ascending manner starting from 1(Like textbox1,textbox2). Now I want that when I click on submit button, it should fire an insert statement which insert all textbox values at once. I know I can do by array, but my question is that how to get all textbox's value in an array and How to perform insert statement?
I have done following code:
Here is PHP Code for submit button:
$schedules = array();
if(isset($_POST['submit']))
{
for($d=1; $d<=$_GET['totalDay'] ;$d++)
{
array_push($schedules,$_POST['txtSchedule'.'$d']);
}
print_r($schedules);
}
Here is the html code:
<form method="post">
<table>
<tr>
<td>Day</td>
<td>Schedule</td>
</tr>
<?php
if(isset($_GET['tour_code']) and ($_GET['totalDay']!=1))
{
$tour_code = $_GET['tour_code'];
$total = $_GET['totalDay'];
$i=0;
do
{
$i=$i+1;
?>
<tr>
<td><?php echo $i;?></td>
<td>
<input name="txtSchedule<?php echo $i;?>" type="text" size="30"/>
</td>
</tr>
<?php
$start = date('Y-m-j',strtotime($start.'+1 days'));
}while($i!=$total);
}
?>
</table>
<input type="submit" name="submit" value="Add Tour Details" />
But I am getting an empty array.
Note: $total is coming through URLString's $GET method.
Below is the output of HTML:
Simplest thing first. You have an error, you can't use
array_push($schedules,$_POST['txtSchedule'.'$d']);
You must use DOUBLE QUOTES on the $d (single quotes won't evaluate d, it will literally read "txtSchedule$d" with a dollar sign, and not actually 0, 1,..., n)
array_push($schedules,$_POST['txtSchedule'."$d"]);
//or no quotes at all
array_push($schedules,$_POST['txtSchedule'.$d]);
(that may sovlve your problems)
But now let's get to how to make an array available to the $_POST object in the processing page via form naming conventions
You're not using array syntax, but you are oh-so close. In PHP, whatever is submitted needs to be of an expected format, and iterating txtSchedule0, txtSchedule1, ...txtScheduleN is not an Array(), but $_POST[] is an array that contains each (given what you've named your input fields, which is missing 1 small thing - square brackets).
What you need to do is be naming your inputs as an array is the array name followed by square brackets (arrayName[]), here is how you create an input array of the name txtSchedule (that way when you print_r($_POST['txtSchedule']) you get an Array())
<input name="txtSchedule[<?php echo $i;?>]" type="text" size="30"/>
I had the same issue when I started in PHP, you were forgetting the square brackets around [<?php echo $i;?>]
Just make sure that if you want to do an iteration over an array of inputs:
for($i=0; $i < count($_POST['txtSchedule']); $i++){
echo "They entered " . $_POST['txtSchedule'][$i] . " in the $i" . "th position";
}
... you have used the <input name="arrayName[$i]"> sytax, or even more simply <input name="arrayName[]"> for it to auto-magically generate an array on submit in the order the inputs were in the HTML page. The naming convention is so important, and since you have it wrong (you used arrayName0, arrayName1, ... arrayNameN instead of arrayName[0], arrayName[1], ... arrayName[n]), it will never be available to you as an array.
if i understand your question correctly you are trying to retrive user input from each textbox and save it in an array?
if so I would use jquery to select all textboxes and loop through them and retrive the value
If you are looking purely at the SQL syntax, then you can just append extra records to insert at the end of your query by providing more value sets:
INSERT INTO myTable (fieldName1, fieldName2) values ("Value1A", "Value1B"), ("Value2A", "Value2B")
If you looking at the PHP logic, then my first suggestion is to use the http POST method instead of GET. Then start with processing the $_POST fields:
$data= array();
foreach($_POST as $key => $value) {
if (preg_match('/^TextBox\d+$/', $key)) {
$data[] = $mysqli->real_escape_string($value);
}
}
The construct the SQL query based on the available data
if (count($data) > 0) {
$sql = 'INSERT INTO `myTable` VALUES("' . implode('"),("', $data).'")';
// log query
// execute query
// process query results
// redirect user to a thankyou page
header('Location: thankyou.php');
}
Note that the code assumes that you have a mysqli connection instance available at $mysqli
Not sure if this is what you are looking for but should give you at least a start..
String []ar=request.getParameterValues("name");
String cmd=request.getParameter("cmd");
if(cmd==null) cmd="";
if(cmd.equals("Submit")){
for(int i=0;i<ar.length;i++) {
insert logic;
<form method="post" action="page3.jsp">
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/> <input type="submit" value="Submit" name="cmd"/>
</form>
Orignal post http://www.daniweb.com/web-development/jsp/threads/197777/insert-dynamic-textbox-value-in-database
Now before we begin let me inform you all that this is just a school assignment and that I am not overly an expert in php and sql coding.
I have the problem, whenever I execute the script, I receive the following error:
Notice: Undefined variable: Team in
C:\xampp\htdocs\NFL\searchmatches.php on line 30.
From my understanding, there would be a spelling error in the link up between the script and the form file, but I can't seem to find the problem.
This is a file to search the database:
Script:
<?php
mysql_connect("localhost","root","0gd1d0wgpg") or die(mysql_error());
mysql_select_db("NFL") or die(mysql_error());
$query=mysql_query("SELECT * FROM Matches where Team ='$Team'") or die(mysql_error());
$numfields = mysql_num_fields($query);
print("<table border=\"1\">\n<tr>\n");
for ($i=0; $i<$numfields; $i++) {
printf("<th>%s</th>\n", mysql_field_name($query,$i));
}
print("</tr>\n");
while ($row = mysql_fetch_row($query)) {
print("<tr>\n");
for ($i=0; $i<sizeof($row); $i++) {
printf("<td>%s</td>\n", $row[$i]);
}
print("</tr>\n");
}
print("</table>\n");
?>
Form:
<form name="addmatch" method="post" action="searchmatches.php">
Search for the match history of a particular team here.<br>
<br>
Team Name: <input type="text" name="Team_Name" value="Team Name">
<br>
<br>
<input type="submit" value="Search">
</form>
Yes there is more coding in the actual files but I figured that, the PHP would be all you needed to help me.
So could somebody please tell me how rid of this error and make the search work.
PHP uses a special "super global" to give you access to submitted form values. The $_POST superglobal is an array with keys that match the name attribute of the form elements (when the form is submitted with the "post" method). Add this line:
$Team = mysql_real_escape_string($_POST['Team_Name']);
above the use of $Team in the query.
To recap, the 'Team_Name' identifier comes from your HTML:
<input type="text" name="Team_Name" value="Team Name">
and then when the form is submitted, whatever you put in that form control is available at $_POST['Team_Name']. I passed the value through the "escape" function so to protect your query from going bonkers (or worse) if that value happened to contain special characters.
I have a form that submits multiple values using php. code is below:
echo "<form action='?ud=".$ud."' method='post'>Name: <input type='text' name='fname' />";
$resultw = mysql_query("SELECT * FROM options where userid='$ud' ORDER BY priority ASC");
while($row = mysql_fetch_array($resultw))
{
echo "
<input type='hidden' name='widgetid[]' value='".$row['widgetid']."' />
<span id='".$row['widgetid']."' style='color:white;font-size:13px;'>".$row['items'] . "</span><br></div><div style='' class='portlet_content'>
Enabled <input title='Enabled/Disabled' type='checkbox' value='enable[]' name='enable[]' ".$checked." id='checkbox".$row['id']."' />
Height <input title='set height' name='height[]' value='".$row['height']."' type='text' name='textfield' id='textfield".$row['id']."' />
";
}
echo '<input type="submit" /></form>';?>
as you can see its a loop thats get the values from db and echoes a form. I made it as simple as possible it has more input boxes but i removed them and removed the styling to make it simpler to read. when I hit Submit I would like to be able to have all those values updated to the database through a loop.
I tried foreach and struggled. any suggestions
First of all, your code has a security bug in that you are directly putting a variable into a SQL query. That allows for SQL injection. Instead, you should put the variable $ud through mysql_real_escape_string before inserting into the query or, significantly better, use MySQLi/PDO and prepared statements.
Have you checked that the form is correctly echoed onto the page? View the source (or use Firefox and Firebug) to double check that it has been properly inserted.
Then you will need to have a code block that is initiated when it receives a POST request. That code will get an array back for each of your variables e.g.
$widget_ids = $_POST['widgetid']; #this will be an array
$enable = $_POST['enable'];
$height = $_POST['height'];
You can do this for each of your POSTed variables and then just loop round the widget ids doing an update query for each one e.g.
$i = -1;
foreach($widget_ids as $widget_id) {
$row_enable = $enable[++$i];
$row_height = $height[$i];
//DO THIS FOR THE REST AND THEN YOUR UPDATE QUERY
}
Just to be pedantic, your HTML is also a bit messy and incorrect. For a form I would use label elements for each label and don't use br's for new lines. You also have a div with no beginning and then a div with no ending.