I have this table:
foreach( //conditionals ){
<td id="changeStatus">
<input type="text" name="rcStatus" value=""/>
</td>
}
The <td>s are blank, and when I click on each one, the bgcolor of the cell changes, and also the value of rcStatus.
I do using this code:
<script>
$('#table #changeStatus').click(
function(){
var cell = $(this);
state = cell.data('state') || 'first';
switch(state){
case 'first':
cell.addClass('red');
cell.data('state', 'second');
this.getElementsByTagName('input')[0].value = "missed";
break;
// other cases here
}
});
</script>
My problem now is that I need to store the value of rcStatus in my database.
What happens is that I am only able to store the most recently set rcStatus.
I'm using PHP.
foreach( //conditionals ){
mysql_query("INSERT INTO `details`(ID, Name, Status) VALUES('NULL','$_POST[name]','$_POST[rcStatus]');");
}
How can I call each individual variable using $_POST even though I'm using the same name/id?
You could append a number to the name of the input field to identify each input field, see also Multiple inputs with same name through POST in php.
you can use this logic.
$i = 1;
foreach( //conditionals ){
<td id="changeStatus">
<input type="text" name="rcStatus<?php echo $i; ?>" value=""/>
</td>
$i++;
}
Change your <tr> to:
foreach( //conditionals ){
<td id="changeStatus">
// giving [] to a name attribute makes it an input array, like #Smutje mentioned
<input type="text" name="rcStatus[]" value=""/>
</td>
}
And in your PHP:
foreach($_POST[rcStatus] as $key=>$val){
mysql_query("INSERT INTO `details`(ID, Name, Status) VALUES('NULL','$_POST[name]','$val');");
}
A few notes:
Please migrate to mysqli_ functions as mysql_ is
deprecated
You are open to SQL Injection . For the time being, till you migrate, you can use mysql_real_escape_string to escape $_POST values
Related
This is my first question on S.O so apologies if this is done incorrectly however I'm stumped as to whether this is even possible let alone how to do it. I have a form and within that form is a dynamically generated table. The user adds defects to a table if they are still outstanding. So the amount of rows will vary every use.
<table class="mytable" id="open-defect-table" name="open-defect-table">
<tr>
<th name="example">Defect ID</th>
<th>Status</th>
<th>Severity</th>
<th>Priority</th>
<th>Assigned To</th>
<th>Defect Link</th>
<th>Summary</th>
<th>Comments</th>
</tr>
</table>
Above is the table that sits on the page normally and whenever the user clicks a button:
<input type="button" name="open-defect-add-button" id="open-defect-add-button" value="Add" onclick="addOpenDefect()">
It adds the details to the table and provides a unique ID to the row.
However I'm not sure how I then go about posting on the form submit to another page..in my case "export.php"
Within the PHP page is this:
<h2>Open Defects: <span>
<?php
$selected_option = $_POST["open-defects-select"];
if ($selected_option == "Yes"){
// What i'm trying to work out
} else {
echo ("None");
}
?></span></h2>
Within that field I want to copy the table that was created within the previous form.
Is this possible? And if so how would I go about or what would be the best way in tackling this?
Any help would be appreciated and again apologies if anything is missing from the details.
You can give a name to each cell on the table, for example, if you have a table with names and phones, all the cells in the column "name" will share the name "name", and all the cells in the column "phone" will share the name "phone". Notice all the cells share the same names, when this happens, they become an array, so, you will have an array of names and another array of phones. Example code:
zzz.html
<html>
<head>
<script type="text/javascript">
function add_row ()
{ var tbl = document.getElementById( "tbl" );
var row = tbl.insertRow( -1 ); // INSERT ROW AT THE END OF TABLE.
var cel = row.insertCell( -1 ); // INSERT CELL AT THE END OF ROW.
cel.innerHTML = "<input type='text' name='name[]'/>"; // ◄■■■ [] ARRAY.
cel = row.insertCell( -1 ); // REUSING THE SAME VARIABLE.
cel.innerHTML = "<input type='text' name='phone[]'/>"; // ◄■■■ [] ARRAY.
}
</script>
</head>
<body>
<button onclick="add_row()">Add row</button>
<form method="post" action="zzz.php">
<table id="tbl" border="1">
<tr>
<td>Name</td>
<td>Phone</td>
</tr>
</table>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
zzz.php
<?php
if ( isset( $_POST["name"] ) && isset( $_POST["phone"] ) )
{ echo "Names: <br/>";
foreach ( $_POST["name"] as $name ) // $_POST["name"] IS AN ARRAY.
echo $name . "<br/>";
echo "<br/><br/>" .
"Phones: <br/>";
foreach ( $_POST["phone"] as $phone ) // $_POST["phone"] IS AN ARRAY.
echo $phone . "<br/>";
}
else echo "Error: no data";
?>
Copy-paste previous codes in files with the given names (zzz.html, zzz.php), then open zzz.html in your browser. Click several times the button "Add row", type some data, then click "Submit". PHP will get the names and phones as arrays and display their contents.
The important thing here is the use of [] :
cel.innerHTML = "<input type='text' name='name[]'/>"; // ◄■■■ [] ARRAY.
All the <inputs named "name[]" will become an array and will be submitted as an array.
The idea is to send the whole table as arrays, one array per column. On the PHP side, you are getting the table's data as arrays, you will be able to re-build the entire table again.
You can use jQuery post for this purpose
var data = {
key1: "value1",
key2: "value2",
key3: "value3"
};
$.post( "ajax/openDefects.php", function( data ) {
$( ".result" ).html( data );
});
see this official documentation for more details.
I'm creating a form from a database and the input id's could be 1-9, 1,2,5,8, etc. IE with the way it is now, I cannot determine what the number will be unless I were to iterate from number 1 to the final number of menu items in the database... which I imagine is not optimal from a coding perspective.
I have two files. File1 will get list number of menu items from a database and create a list. The condensed version of my code is as follows, please keep in mind i have condensed a lot of useless stuff;
File1.php
$menuArray = openMenu(1);
$return = "<div id='menu'><form method='post' action='file2.php'><input type='submit' name='submit' value='Commit Order' /><table class='tableinfo'>";
$i=1;
foreach($menuArray as $recordNum => $record)
{
if ($record['available'] > 0)
{
$thisClass='available';
} else{
$thisClass='unavailable';
}
$return.="<tr class='$thisClass'>
<td>$record[itemid]</td>
<td><label for='$record[itemid]'>$record[name]</label></td>
<td><button type='button' id='itemid-$record[itemid]' class='subtract'>-</button><input class='itemadder' id='itemid-$record[itemid]' type='number' min='0' value='0' /><button id='itemid-$record[itemid]' class='addition' type='button'>+</button></td>
</tr>";
}
$return.="</table></form></div>";
return $return;
File2.php
I don't know how to code this :(
Is anyone able to shed some light on the best way to do this?
I just need a way to be able to see what id's have a value when posted.
I am using jQuery at the moment; would this be something best done using jquery?
Assuming I understand you correctly the best way to do this would be to have an array of inputs.
Code you should try to achieve for your HTML output would need to be something like this:
<input type="text" name="number[1]" value="" />
<input type="text" name="number[3]" value="" />
<input type="text" name="number[5]" value="" />
Now you know after your form submission in PHP:
foreach($_POST['number'] as $id => $value){
echo 'The value for ID #' . $id . ' is ' . $value;
}
The script File1.php rendering the inputs above does know about what has rendered out. So what, if it also puts a list of rendered form element names in to the session for later use in file2.php:
In the beginning:
$_SESSION['formids'] = array();
in the loop:
....
$_SESSION['formids'][] = "itemid-" . $record[itemid];
and in file2.php:
$sendItems = $_SESSION['formids'];
...
foreach ( $sendItems as $itemId )
{
$val = empty($_POST[$itemId]) ? null : $_POST[$itemId];
if ( isset($val) )
...
I have a form that will send data via POST. I want that data to go to different MySQL tables based on the POST "name."
What I have so far is a while loop for the form fields that will name each input in the format: "name"{}$id. I thought that using {} as a delimiter I could then use explode() and use a conditional statement to select which table the data should go to.
Is this the best way to do this? The issue I'm having is also calling the name, since using foreach for example on POST will just return the values and not the names. I have enclosed the code below:
<?php while ($cred = mysql_fetch_array($credentials_process)) { ?>
<div class="edit-profile-background-inputs">
<span><input type="text" name="cred{}<?php echo $cred['id']; ?>" value="<?php echo $cred['credentials']; ?>" /></span>
<span style="margin-left:10px;">Remove</span>
</div>
<?php } ?>
I need those fields named cred{} to go to credentials table, those named edu{} to go to the education table, etc.
<input type="text" name="cred[<?php echo $cred['id']; ?>]"...
<input type="text" name="edu[<?php echo $edu['id']; ?>]"...
in PHP
$insert=array();
foreach ($_POST['cred'] as $k=>$v)
{
$insert[$k]=mysql_real_escape_string($v); // yes I know mysql is being depreciated
}
$sql='INSERT INTO cred ('. implode(',', array_keys($insert)).') VALUES ('. implode(',', $insert).');
repeat for $_POST['edu']
If your results set is such that you're outputting more than one row with the same key
$i=0;
while ($cred = mysql_fetch_array($credentials_process)) { ?>
<input type="text" name="cred[$i][<?php echo $cred['id']; ?>]"...
...
$i++;
}
If you print_r($_POST) from that you'll be able to figure out how to deal with them.
NB. For safety I would also make sure only the expected posted vars get used
$allowed=array('cred_id', 'cred_something', 'etc');
foreach ($_POST['cred'] as $k=>$v){
if (!in_array($k, $allowed)) continue;
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
I have a form
<form action="_orders.php" method="get" autocomplete="off" name="cerca_db">
<tr>
<td class="main" width="170">Ricerca Cliente</td>
<td><input type="hidden" name="action" value="check_sped_data" /></td>
<td class="main"><p class="ciao" id="auto"><input id="searchField" name="searchField" type="text" onKeyPress="return disableEnterKey(event)"></p></td>
<td width="25"></td>
<td class="main"><input type="submit" value="Cerca"></td>
</tr>
</form>
This is used to search in a mysql db table. Once the button is clicked it autocompletes all fields of another form based on the database record just found.
Now my problem is with autocomplete part because of case sensitive. I have already managed to extract data in lower case but i'm not able to transform input
searchField to lower case before send to java function to match db record.
I actually found javascipt function to have autocomplete stuff. I only changed html and php part to match my needs, I didn't touch anything on java itself because i'm totaly a noob with it.
So now the form send the input to the javascript like this
$(function(){
setAutoComplete("searchField", "results", "autocomplete.php?part=");
});
The automcomplete.php is need to extract data from db based on input and place in array to display under the input:
$result = mysql_query("SELECT a.customers_firstname, a.customers_lastname, a.customers_id, b.entry_company FROM customers a left join address_book b on a.customers_id = b.customers_id GROUP BY b.entry_cf");
while ($row = mysql_fetch_assoc($result))
{
$ricerca = array(strtolower($row['customers_firstname']) => strtolower($row['customers_lastname']));
foreach ($ricerca as $key=>$data)
{
$edata[]=$data . ' ' . $key;
$edata[].=$key .' ' . $data;
}
$edata[].=(strtolower($row['entry_company']));
}
Now we have the array of names and company all lower case ready to match what is entered in the field. If the input is lowercase everything works fine, but if input is uppercase it doesn't match anything at all.
Do you guys have any solution on this or any idea how i can workout the case sensitive problem?
Edited: this is how data are pushed from db to the java script:
if(isset($_GET['part']) and $_GET['part'] != '')
{
$results = array();
$count = 0;
foreach($extracted_data as $edata)
{
if( strpos($edata, $_GET['part']) === 0 )
{
$results[] = $edata;
$count++;
if ($count == 10) break;
}
}
echo json_encode($results);
}
Before submitting or sending information, call a javascript function which converts all characters to lowercase.
If your element is named "YourInputID",
Example:
function convert()
{
var a = document.getElementById("YourInputID").value;
a = a.toString().toLowerCase();
document.getElementById("YourInputID").value = a;
}
You could use javascript string function reference here str.toLowerCase() to convert the string characters to lower.
This should get you on the right track:
document.getElementById('foo').addEventListener('keypress', function(e) {
e.preventDefault();
this.value += String.fromCharCode(e.keyCode).toLowerCase();
});
Demo: http://jsfiddle.net/m66c2/
OK, firstly your PHP is going to have some problems. Where you say:
$edata[]=$data . ' ' . $key;
$edata[].=$key .' ' . $data;
That's going to access two different items in the array, which I assume you don't want to do. That's because the syntax $array[] is (sort of) short for using the array_push() method - each time it is accessed it adds to the array. The syntax $array[].=$value means the same as $array[]=$value as you can't effectively concatenate to an empty array item.
$edata_this='';
foreach ($ricerca as $key=>$data)
{
$edata_this=$data . ' ' . $key;
$edata_this.=$key .' ' . $data;
}
$edata_this.=(strtolower($row['entry_company']));
$edata[]=$edata_this;
Now, if your issue is simply converting a JavaScript item to lower case, use the String.toLowerCase() method.
However I'm not entirely sure in the question which part you're actually needing to change or do a comparison on, so some more explanation might be useful.
Additionally you should always avoid using inline JavaScript such as onKeypress; as you're using jQuery try using its $().keypress() binding:
$('input[name="YOUR_NAME"]').keypress(function(){
// your actions go here
});