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
});
Related
I've got a search function written in PHP/MySQL which works fine. What I want to happen is that when a user produces a search they can click a button which will submit the $id from the output to a table in my database.
I've copied my code below, the error is within the php echo in the form, it just displays the plain text of the php code.
Everything else works fine, I've tested this by setting value to "" and entering the id myself and then it works. I want it though to be a hidden input in future where the id automatically comes through from the search result. Multiple searches can be returned on the same page and this form is underneath each individual search result.
<?php
$conn = mysqli_connect("localhost","root","","users");
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$query = mysqli_query($conn, "SELECT * FROM users WHERE main LIKE '%".$search."%'") or die ("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = "There was no search results!";
}else{
while ($row = mysqli_fetch_array($query)) {
$id = $row ['id'];
$main = $row ['main'];
$postcode = $row ['postcode'];
$available = $row ['available'];
$email = $row ['email'];
$output .='<div><br><b>Player ID: </b>'.$id.'<br><b>Main:
</b>'.$main.'<br><b>Postcode: </b>'.$postcode.'<br><b>Available:
</b>'.$available.'<br>
<br>
<form action="request_player.php" action="post">
<input type="text" name="id" value="<?php echo $id ?>">
<input type="submit" value="Request Player">
</form>
</div>';
}
}
}
echo $output;
?>
<br> Back to your account
The issue Jay Blanchard highlighted and which you took a bit lightly - perhaps b/c you fear the distraction from your current problem - is actually pretty related to the issue you highlight in your question.
This btw. is nothing uncommon. In this little script you deal with at three languages: HTML, SQL and PHP. And all these are intermixed. It can happen that things jumble.
There are methods to prevent these little mistakes. What Jay highlighted was about how to encode a SQL query correctly.
The other problem is to encode a HTML string correctly. Let me highlight the part:
$output = '... <input type="text" name="id" value="<?php echo $id ?>"> ...';
In this PHP string you write "<?php echo $id ?>" verbatim, that means, this will echo'ed out then.
What you most likely meant was to write it this way:
$output = '... <input type="text" name="id" value="' . $id . '"> ...';
So this seems easy to fix. However, it's important that whether it is SQL or HTML, you need to properly encode the values if you want to use them as SQL or HTML. In the HTML case, you must ensure that the ID is properly encoded as a HTML attribute value. In PHP there is a handy function for that:
$output = '... <input type="text" name="id" value="' . htmlspecialchars($id) . '"> ...';
Or as the ID is numeric:
$output = '... <input type="text" name="id" value="' . intval($id) . '"> ...';
works similarly well.
You need to treat all user-data, that is all input - which includes what you get back from the database (!) - needs to be treated when you pass it into a different language, be it HTML, SQL or Javascript.
For the SQL Jay has linked you a good resource, for the HTML I don't have a good one at hand but it requires your own thoughtfulness and the will to learn about what you do (write) there. So sharpen your senses and imagine for each operation what happens there and how this all belongs together.
One way to keep things more apart and therefore help to concentrate on the job is to first collect all the data you want to output and then process these variables in a template for the output. That would prevent you to create large strings only to echo them later. PHP echoes automatically and a benefit of PHP is that you can use it easily for templating.
Another way is to first process the form input - again into your own variable structure - which is the programs input part and run first. Then follows the processing of the input data, in your case running and processing the database query. And after that you care about the presentation. That way you have common steps you can become more fluent in.
I hope this is understandable. It's full of further obstacles, but it pays to divide and conquer these programming problems. It will also help you to write more while you need to write less for that.
And btw., you don't need to switch to PDO, you can stick with Mysqli.
The reason it is happening is because you have put <?php echo $id ?> inside a string. You want to do the same thing you did elsewhere in your example: value="' . $id . '" It can quickly get confusing when you have single and double quotes happening together. You might be best off learning how to use PHPs multiline strings.
Also, <?= $id ?> is a useful shorthand for <?php echo $id ?> (although you don't want to use either here)
I have a MySQL database with auto-increment column "line numbers." In the form that is being submitted to the script, there are check boxes. I don't know how many check boxes there are, because each Customer has a different number of services that they're allowed to access. When the check box is clicked, they've used a service and the integer in column Available for that row needs to decrease by one. Sometimes, the user can say that multiple services were used and more than one row needs to be affected.
Where I'm becoming stuck is on two things: how the check boxes are named, and if I name them by the line number, how to access them with PHP.
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='" . $cell['line_item'] . "'>";
}
The above code is how I'm making the check box. Probably the biggest part of the question is how I could better name it so that I can predict what names to look for ($_POST[name]) when the form is submitted (instead of a random number).
The other part I'm getting stuck on is, if I do decide to keep the naming strategy, how to fetch it. What I've thought of is to use a loop to extract the true/false data that's carried, but I don't know how to execute that. Sure, I can write a for or while loop, but I don't know how to extract the name of the object.
Is there any way I could carry extra data to a PHP script, other than the name?
Is there a better way I could name the check box so that I'm not stuck having to figure out a complicated way of finding the data, retrieving the name, etc.
I'm sort of a beginner when it comes to PHP. I know how to get my way around with for loops, while loops, basic commands such as echo... but I'm really lacking
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='checkboxname[]' value ='".$cell['line_item']."'>";
}
It should do a $_POST array with the name checkboxname inside that array, you find the values.
You can find it threating $_POST['checkboxname'] as an array.
Try name it like: "checkbox_" . $cell['line_item'] so you can do something like this:
foreach($_POST as $name => $value)
{
if(substr($name, 9) == "checkbox_"){
//USE the value
}
}
or you could name like this:
echo "<input type='checkbox' name='services[]' value='" . $cell['id'] . "'>";
and get it as an array like this: $services = $_POST["services"];
Alright. Since you wanted to be able to add extra data, I thought I'd start over complicating stuff a lot! But it does the job. Explanation can be found in the codes comments.
First the HTML and Javascript part:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
// First we need to get our form
var myForm = document.getElementById("myForm");
// Next we're adding an event listener to the form submit so we can catch it
// and use a function to do some stuff before sending it over to the php file
myForm.addEventListener("submit", function(event){
// Now we need to temporarely stop the form from submitting
event.preventDefault();
// Next we need to get all our checkboxes
var checkBoxes = document.getElementsByClassName("myCheckbox");
// Now we need some arrays for all the data we're going to send over
// Basicly you make one for each data attribute
var lineNr = [];
var someThing = [];
// Lets loop through all checkboxes
for (var i=0; i<checkBoxes.length; i++) {
// Catch the ones checked
if (checkBoxes[i].checked) {
// Push the data attribute values to the arrays
lineNr.push(checkBoxes[i].dataset.linenr);
someThing.push(checkBoxes[i].dataset.something);
}
}
// Now we to JSON encode these arrays to send them over to PHP
var jsonLineNr = JSON.stringify(lineNr);
var jsonSomeThing = JSON.stringify(someThing);
// Since we cannot directly add these variables to our form submit,
// unless we use Ajax, we need to add them to our form in some
// hidden fields
myForm.innerHTML += "<input type='hidden' name='jsonLineNrs' value='"+ jsonLineNr +"' />";
myForm.innerHTML += "<input type='hidden' name='jsonSomeThings' value='"+ jsonSomeThing +"' />";
// All done, now we submit our form
myForm.submit();
}
</script>
</head>
<body>
<form method="POST" action="your_php_file.php" id="myForm" accept-charset="utf-8">
<input type="checkbox" class="myCheckbox" data-linenr="1" data-something="value1" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="2" data-something="value2" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="3" data-something="value3" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</form>
Next the PHP part:
<?php
// First we need to decode the JSON strings so we can use them
$jsonLineNrs = json_decode($_POST['jsonLineNrs']);
$jsonSomeThings = json_decode($_POST['jsonSomeThings']);
// Now both of those variables are arrays that contain all the data you wanted
// You can loop each of them to do stuff like
foreach($jsonLineNrs as $jsonLineNr){
echo $jsonLineNr; //Will echo out each line number
}
// Or if you want to loop through both simultaneously so you can
// keep each checked box data values together:
for($i=0; $i<count($jsonLineNrs)-1; $i++) {
echo $jsonLineNrs[$i].' - '.$jsonSomeThings[$i];
}
?>
Now before I finish this answer, one last warning: I didn't sanitize the user input in the Javascript part. It would make this answer even a lot more complicated and way to long. Be sure to do this, as you can NEVER EVER trust user input! Even if it's only checkboxes, POST data can be changed before it's submitted!
I would prefix the names depending on context, for example:
<input type='checkbox' name='service_" . $cell['line_item'] . "'>"
This way, if the checkbox represents a service, you could identify it by the prefix.
I'm building a form - a section of which dynamically generates and increments input field's individual ids when the user hits the 'replicate' button. For instance, an input field made for a first name has an id of 'firstname1', when it replicates it becomes 'firstname2' etc etc.
My problem is in the php 'confirmation' page I'm trying to build. I want to echo out every input field generated and filled without hardcoding a bunch of echoes. I was told to use arrays instead of individual variable names - i kind of understand the concept but am falling way short.
I tried to create an array to capture the value of every new input so I can just $_POST the array, then loop and echo each value, but I don't really understand what needs to change and where to implement it.
The following code replicates the entire container div, it's input fields, and increments it's class number:
$(#replicate').click(function(){
var $cloned = $('.container1').clone();
$cloned.find('input').val('');
$cloned.appendTo($('.emptyContainer'));
var container = $(".emptyContainer div").length;
var containerNumber = container + 1;
var containerClass = 'container' + containerNumber;
$(".emptyContainer .container1").attr("class", containerClass);
Then the input ids increment in the same fashion:
var fnameID = 'firstname' + containerNumber;
$('.emptyContainer #firstname1').attr({id: fnameID, name: fnameID});
There are more inputs that would include things like last name, phone, email etc.
Another user suggested:
foreach($_POST as $fieldName=>$fieldValue){
echo $fieldName." = ".$fieldValue."<br/>";
}
While that worked to get me everything on the php page it was all in one large block, which would make the later styling a bit troubling.
How do I grab the input values for each new input, store them in an array, and post them to the php side in such a way that all related information stays in it's related areas when the user hits submit?
You can try following method, as this method works best for me in case of dynamic rows.
code is not much readable since i directly pasted from the project but still hope it would be helpful
$('.add-option').live('click',function(){
if(rowCtr < ucount){
var tr = '<tr class="input-'+counter+'"><td><select id="itb_users" class="itb_users" name="project[itb_users]['+counter+']" >'
tr += '<option value=0>Select</option>'
<?php foreach ($itb_users as $item){ ?>
tr += '<option grade="<?php echo $item->grade; ?>" value="<?php echo $item->id; ?>"><?php echo $item->first_name; ?></option>';
<?php } ?>
tr += '</select>'
tr += '</td>'
tr += '<td> </td>'
tr += '<td><input class="_hour" id="project[input-hour]['+counter+']" name="hours['+counter+']" type="text" class="field" style="width:30px"/></td>'
tr += '<td><img class="add-option" src="'+'<?php img_src('add.png'); ?>'+'" /> <img class="remove-option" src="'+'<?php img_src('remove.png'); ?>'+'" /></td>'
tr += '</tr>';
counter++;
rowCtr++;
.......
on submitting the php will receive a variable project with related records.
I have a small form, where I list an array $menu as checkboxes.
Using jQuery (see script below) I then put the values of the checkboxes into an ( eventually hidden ) input field. I know this is not traditional way , But I want to store them all as a single united value.
When loading the form again (or after submitting) I of course need to populate those fields again with the value that was stored as a string ( from the input field ).
I use a simple strpos() with a ternary operator for "checked".
My problem is that on every load , the FIRST value that is checked on the list , will NOT be confirmed and will not be checked . Always the first one and only the first one (which is upper in the list - and I do not mean the ABSOLUTE first, but the first one to be previously checked . the first in the saved string.). Meaning that If I show the input field ( not hidden ), I can see the value in the string , but the checkbox is not "checked".
all the rest is working well....
Maybe only my eyes are tired , but I can really not find where the problem is :-)
Any input will be greatly appreciated ..
global $menu;
$output = '';
for ($i = 1; $i <= 100; $i++){
if ($menu[$i][2]){
$find = $menu[$i][2];
$pos = strpos($opp_array['brsa_menu_list'], $find);
$output .= '</br><input class="checkbox remove_check" type="checkbox" ' .(($pos) ? ' checked ':'') . 'name="option1" value="' . $menu[$i][2] .'"> ' . $menu[$i][2] ;
}
}
echo '<b>Available menus : </b><br>' . $output .'<br>';
?>
<p>
<input class="regular-text" id="sbrsamenu_list" name="brsa_s[brsa_menu_list]" type="text" value="<?php echo $opp_array['brsa_menu_list']; ?>"/>
<label class="description" for="sbrsamenu_list">
</br><?php echo 'Please write the menu items'; ?>
</label>
</p>
and the js
<script type="text/javascript">
// <![CDATA[
jQuery(document).ready(function() {
var $checkboxes = jQuery(".remove_check");
$checkboxes.on('change', function() {
var ids = $checkboxes.filter(':checked').map(function() {
return this.value;
}).get().join(' | ');
jQuery('#sbrsamenu_list').val(ids);
});
});
// ]]>
</script>
If $pos is meant to be a boolean value, indicating whether a string appears in another, you should compare the value from strpos() against false:
$pos = strpos($opp_array['brsa_menu_list'], $find) !== false;
Otherwise, if $find appears at the start of your string, strpos() returns 0 which in your code would be equivalent to false.
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