I have an HTML input form that is being sent as a PHP_SELF and then stored on a MySQL table. The input field is dynamically controlled with JS. There are 4 inputs: number (text), amount (int), Approval (text), and Date (text). There inputs are all arrays when they are sent to the PHP file via POST. They're stored in a MySQL table with column fields as: ID (primary key), num (text(4)), amnt (decimal(8,2)), app (text(10)), and date (varchar(10)). I'm getting three significant errors when I try to run the page.
If a number such a 0125 is entered in the number field on the form, it is stored as 125 in the MySQL table. This is regardless of the fact that the field is being stored as a text string.
The Approval field works perfectly fine when only integers are entered, however, when only text or a combination of text and numbers is inserted, the MySQL query produces the following error: Error: Unknown column 'aft859' in 'field list'. For example, when 853234 is entered, everything goes through fine, but when aft859 is entered, the error is produced.
When a date is entered, it gets inputted into the MySQL table as a decimal value. For example, a date of 08/07/2012 is saved as '0.00056802'.
I have checked every line to make sure that nothing is being converted in the PHP or HTML process, and I've echoed every line to make sure that the values are being handled properly. After much debugging, I'm lead to believe that the following two sections might be causing my problem:
//Check To See If User Has Already Created Table
$sql = "CREATE TABLE IF NOT EXISTS $tablename_cc (
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
cc_num TEXT(4),
cc_amnt DECIMAL(8,2),
cc_app TEXT(10),
cc_date VARCHAR(10)
);";
or it might be this:
if (!mysql_query('INSERT INTO ' .$tablename_cc. '(cc_num, cc_amnt, cc_app, cc_date) VALUES '.implode(',',$pairs)))
die('Error: ' . mysql_error());
else
echo '<strong>', "Your information have been submitted and will be added to your account upon approval.", '</strong>', "</br>", "</br>", "</br>";
I'm not too familiar with PHP, HTML, or MySQL (this is my first program ever), and I'm not sure if I've missed something. I tried to check all quotes and make sure they were right. I'm running all this in Wordpress, just in case that's culprit. Here is my code in its entirety for reference:
<?php
if(isset($_POST['submit']))
{
//Get Current User Login
global $current_user;
$current_user = wp_get_current_user();
$ulog = $current_user->user_login;
$tablename_cc = "cc_".$ulog;
//Check To See If User Has Already Created Table
$sql = "CREATE TABLE IF NOT EXISTS $tablename_cc (
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
cc_num TEXT(4),
cc_amnt DECIMAL(8,2),
cc_app TEXT(10),
cc_date VARCHAR(10)
);";
mysql_query($sql);
$cc_num = $_POST['cc_num'];
$cc_amnt = $_POST['cc_amnt'];
$cc_app = $_POST['cc_app'];
$cc_date = $_POST['cc_date'];
$items = array_map(null,$cc_num,$cc_amnt,$cc_app,$cc_date);
$pairs = array();
foreach ($items as $sub) {
if(implode(',', $sub) != ",,,")
$pairs[] = '('.implode(',', $sub).')';
}
echo implode(',',$pairs);
if (!mysql_query('INSERT INTO ' .$tablename_cc. '(cc_num, cc_amnt, cc_app, cc_date) VALUES '.implode(',',$pairs)))
die('Error: ' . mysql_error());
else
echo '<strong>', "Your information has been submitted and will be added to your account upon approval.", '</strong>', "</br>", "</br>", "</br>";
}
?>
<!--raw-->
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script src="jquery.maskedinput.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.ccinput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
$("*#date").mask("99/99/9999");
// business rule: you can only add 20 names
if (newNum == 20)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.ccinput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$("*#date").mask("99/99/9999");
});
</script>
</head>
<body>
Please fill in your information in the form below and press submit. If you need to add more, please click the "Add" button at the bottom of the form. You may enter a maximum of 20 at a time. Leave all unused fields blank.
<form method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<fieldset>
<legend>Information:</legend>
<div id="input1" class="ccinput">
# (last 4 digits): <input id="cnum" type="text" name="cc_num[]" maxlength="4" size="4" /> CC Amount: <input id="camnt" type="int" name="cc_amnt[]" /> Approval Code: <input id="appr" type="text" name="cc_app[]" maxlength="10" size="10" /> Date: <input id="date" type="text" name="cc_date[]" /> </br>
</div>
<div id="input2" class="ccinput">
# (last 4 digits): <input id="cnum" type="text" name="cc_num[]" maxlength="4" size="4" /> CC Amount: <input id="camnt" type="int" name="cc_amnt[]" /> Approval Code: <input id="appr" type="text" name="cc_app[]" maxlength="10" size="10" /> Date: <input id="date" type="text" name="cc_date[]" /> </br>
</div>
<div id="input3" class="ccinput">
# (last 4 digits): <input id="cnum" type="text" name="cc_num[]" maxlength="4" size="4" /> CC Amount: <input id="camnt" type="int" name="cc_amnt[]" /> Approval Code: <input id="appr" type="text" name="cc_app[]" maxlength="10" size="10" /> Date: <input id="date" type="text" name="cc_date[]" /> </br>
</div>
<div id="input4" class="ccinput">
# (last 4 digits): <input id="cnum" type="text" name="cc_num[]" maxlength="4" size="4" /> CC Amount: <input id="camnt" type="int" name="cc_amnt[]" /> Approval Code: <input id="appr" type="text" name="cc_app[]" maxlength="10" size="10" /> Date: <input id="date" type="text" name="cc_date[]" /> </br>
</div>
<div id="input5" class="ccinput">
# (last 4 digits): <input id="cnum" type="text" name="cc_num[]" maxlength="4" size="4" /> CC Amount: <input id="camnt" type="int" name="cc_amnt[]" /> Approval Code: <input id="appr" type="text" name="cc_app[]" maxlength="10" size="10" /> Date: <input id="date" type="text" name="cc_date[]" /> </br>
</div>
<div>
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnDel" value="Remove" />
</div>
</fieldset>
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
<!--/raw-->
The reason your text values are being truncated (losing leading zeros) is because you're inserting them as numbers and MySQL is dropping the leading zero, and the dates are becoming decimals is because you're inserting them as equations and MySQL is evaluating them.
The reason for this is this line:
$pairs[] = '('.implode(',', $sub).')';
None of the values are surrounded by quotes. You can fix this with:
$pairs = '("'.implode('","', $sub).'")';
Then, you're using implode() again on the already imploded list on the line:
if (!mysql_query('INSERT INTO ' .$tablename_cc. '(cc_num, cc_amnt, cc_app, cc_date) VALUES '.implode(',',$pairs)))
Update this line to:
if (!mysql_query('INSERT INTO ' .$tablename_cc. '(cc_num, cc_amnt, cc_app, cc_date) VALUES ' .$pairs . ))
if (!mysql_query('INSERT INTO ' .$tablename_cc. '(cc_num, cc_amnt, cc_app, cc_date) VALUES '.implode(',',$pairs)))
You need to wrap the input values in apostrophes; otherwise, they'll be treated as numbers - that's why you get the Unknown column error and the date is treated as a sum and not a date.
if (!mysql_query("INSERT INTO " .$tablename_cc. " (cc_num, cc_amnt, cc_app, cc_date) VALUES '".implode("','",$pairs) . "'"))
I think that will do it.
Related
This is the output of my code
Every item has its own item number. I will be entering randomly a value for 3 items, after doing so I will click on the add button and will be redirected to a confirmation page. How will I get the values with its corresponding item?
Thanks in advance for the answers :)
Use input name as array.
<input type="text" name="price[]" />
<input type="text" name="price[]" />
<input type="text" name="price[]" />
<input type="text" name="price[]" />
<input type="text" name="price[]" />
Get values like this
$price = $_POST['price'];
foreach($price as $key => $val ) {
echo $val;
echo "<br>";
}
You can bind or keep the text box name same as your database row ID so when you submit and in the target page you can redo the select and update the field in the database like
<input type="text" name="$id" />
in the target page use Select Query looping and give
Update table_name set field_name=$_REQUEST[$id] where id=$id
Updated
This is the whole code.
Still i do not have a value in the text field "user" but i have in all others.
I print the values before adding them to the db ( deleted it from the original code already - i have all values instead the one in the user field )
This is a testing environment.
What I have issues with, is the following:
the field "user" is a field containing text and for some reason the $_post do not contain it.
all the others variables from the number fields are carried in $_post[field_name], but not the text field.
Do you have any idea how to fix this?
I tried with using html special char, but still no results.
Thanks in advance for the help !
this is the html
<html><head><title>MySQL Table Viewer</title></head><body>
<form action="submit.php" method="POST">
Day: <input type="number" name="day"/> Month: <input type="number" name="mont"/> Year: <input type="number" name="year"/>
<br> <br>
Start Hour:<br>
<input type="number" name="shour"/>
<br>
End Hour:<br>
<input type="number" name="ehour"/>
Agent: <input type="text" name="user" value=""/>
<input type="submit" class="button" name="submit" value="submit" />
</form>
</body></html>
this is the php
<html>
<body>
<?php
$day = mysql_real_escape_string($_POST['day']);
$mont= mysql_real_escape_string($_POST['mont']);
$year = mysql_real_escape_string($_POST['year']);
$shour = mysql_real_escape_string($_POST['shour']);
$ehour = mysql_real_escape_string($_POST['ehour']);
$user = mysql_real_escape_string($_POST['user']);
$con = mysql_connect("localhost","root","samokow");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("reservations", $con);
$sql="INSERT INTO reservations (day, mont, year, shour, ehour, user)
VALUES ('$day', '$mont','$year', '$shour','$ehour','$user')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Booking done." ;
mysql_close($con);
?>
</body>
</html>
You're quoting your $_POST[] you should do it like this:
$sql="INSERT INTO reservations (day, mont, year, shour, ehour, user) VALUES (".mysql_real_escape_string($_POST['day']).", ".mysql_real_escape_string($_POST['mont']).",".mysql_real_escape_string($_POST['year']).", ".mysql_real_escape_string($_POST['shour']).",".mysql_real_escape_string($_POST['shour']).",".mysql_real_escape_string($_POST['user'])."))";
this should work.
You don't have to qoute variables such as post in your query but instead use mysql_real_escape_string
EDIT:
Your year tag is invalid you end it with an $, and in your query you're getting shour 2 times
`Year: <input type="number" name"year"$`
Should be: Year: <input type="number" name="year">
$_POST[day]', '$_POST[mont]','$_POST[year]', '$_POST[shour]','$_POST[shour]'
shouldn't the second shour be ehour?
I hope this code is for testing purposes only?
Paste all of this in the same page!
<form method="POST">
Day: <input type="number" name="day" />
Month: <input type="number" name="mont" />
Year: <input type="number" name="year" />
Start Hour: <input type="number" name="shour" />
End Hour: <input type="number" name="ehour" />
Agent: <input type="text" name="user" />
<input type="submit" class="button" name="submit" value="submit" />
</form>
Before including the $_POST values in your database, you should use mysql_real_escape_string() Just like the others said.
ALSO, you will have to use mysqli or PDO because mysql_query() is deprecated.
if(isset($_POST['submit'])){
$day = mysql_real_escape_string($_POST['day']);
$mont= mysql_real_escape_string($_POST['mont']);
$year = mysql_real_escape_string($_POST['year']);
$shour = mysql_real_escape_string($_POST['shour']);
$ehour = mysql_real_escape_string($_POST['ehour']);
$user = mysql_real_escape_string($_POST['user']);
$sql="INSERT INTO reservations (`day`, `mont`, `year`, `shour`, `ehour`, `user`) VALUES ('$day', '$mont','$year', '$shour','$shour','$user')";
}
I would recommend to provide a valueparameter in the input tag as well:
.... Agent: <input type="text" name="user" value="">
some browsers are picky about that (MS IE ...?)
Try this :
$day = mysql_real_escape_string($_POST['day']);
$mont= mysql_real_escape_string($_POST['mont']);
$year = mysql_real_escape_string($_POST['year']);
$shour = mysql_real_escape_string($_POST['shour']);
$ehour = mysql_real_escape_string($_POST['ehour']);
$user = mysql_real_escape_string($_POST['user']);
$sql="INSERT INTO reservations (day, mont, year, shour, ehour, user) VALUES ('$day', '$mont','$year', '$shour','$shour','$user')";
you need to put the row in quotes like this:
$_POST['user']
Hi I'm quite new to php and I'm currently making a webpage similar to the ones used by supermarkets for stock management control as part of an assignment. I have the following form where the cashier would enter the product Id and the quantity of the item being purchased.
The form will then call another php file named cashsale.php which will take these inputs and update the tables in my database so that levels of stock on shelves in supermarkets are up to date with the new amounts (i.e. older qty - qty entered) and management can be advised when reorder is needed.
As it is the form works well, however I was advised to edit it in a way that a cashier can enter multiple products and quantities before submitting (i.e. the form will sort of show itself again) and allow the user to edit or remove any items before actually submitting the values to cashsale.php to manipulate the tables. I seem to be at a loss as to how this can be done.
I wanted to create a new button named "Add" which would display the form again, i.e. allow the user to check in more items, but I am confused as to how this can be done and also as to how I will be able to update tables then since I would be having more then just 2 inputs.
Can anyone help me on this please? Thanks in advance. The following is my html form:
center form action="cashsale.php" method ="post"
Product ID: <input name= "id" type="int" > <br>
Quantity:<input name="qty" type="int">
<input type="button" name = "Add" onclick="add">
<input type="Submit" name ="Submit" value = "Submit">
form center
I was not allowed to use html tags for form and center so I removed the < >. The following is some of the modifications done in the cashsale.php file just to give a clearer example.
$result = mysql_query("SELECT * FROM shelfingdetails where prodId =' " .$id. " '");
if (!$result){
die (mysql_error());
}
while ($row =mysql_fetch_array($result))
{
$qtyOnShelf= $row ['QtyOnShelf'];
$max=$row['max'];
$newQtyShelf=$qtyOnShelf-$qty;
}
$update=mysql_query("UPDATE shelfingdetails SET QtyOnShelf ='". $newQtyShelf. "' where prodId = '". $id. "';");
I hope someone can help. Thanks!
You just have to pass an array. For this you have to generate the inputs with PHP or javascript (I'm gona use jQuery to keep the code nice and simpe).
If you use PHP:
// PHP
<?php
if(isset($_POST['submit']) && $_POST['submit']){
//save data
} elseif(isset($_POST['Add']) && $_POST['Add']) {
$max = (int)$_POST['max']
} else { $max = 1; }
?>
<form action="" method="post">
<?php
for($i = 0;$i < $max;$i++){
?>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
<?php
}
?>
<input type="hidden" name="max" value="<?= $i; ?>" />
<input type="submit" name="Add" />
<input type="submit" name="Submit" value="Submit" />
</form>
If yo use Javascript:
//HTML
<form action="" method="post" id="form">
<div id="add">
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
</div>
<input type="hidden" name="max" value="<?= $i; ?>" />
<input type="button" name="Add" onclick="addRow();" />
<input type="submit" name="Submit" value="Submit" />
</form>
// jQuery
function addRow(){
$("#add").append("<br />Product ID: <input name='id[]' type='int' >" +
"<br />Quantity: <input name='qty[]' type='int'>");
}
you have to use id[] and qty[] to pass them as an array and with the add button generate as many of them as you need. Like so:
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int"> <br>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int"> <br>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
<input type="button" name = "Add" onclick="add">
Then on the backand use for loop to save all the data.
$max = count($_POST['id']);
$id = $_POST['id'];
$newQtyShelf = $_POST['qty'];
for($i = 0;$i < $max;$i++){
$update=mysql_query("UPDATE shelfingdetails
SET QtyOnShelf ='". (int)$newQtyShelf[i]. "'
WHERE prodId = '". (int)$id[i]. "';");
}
I just wanted to show you the idea, please don't use this specific code, because you should use mysqli instead of mysql and also mysqli_escape_string to make sure that the user not submits incorrect data.
I have multiple inputs
<input size="32" class="mixtapetrack" type="text" id="track[]" name="track[]" >
<input size="32" class="mixtapetrack" type="text" id="track[]" name="track[]" >
<input size="32" class="mixtapetrack" type="text" id="track[]" name="track[]" >
<input size="32" class="mixtapetrack" type="text" id="track[]" name="track[]" >
...and so on (depending on how many they want)
On form submit (using $_POST), i want to take all of the inputs (which by the way, we'll never now how many will be there [dynamic jquery add/remove input form] ) and combine them into one variable, all nicely separated by ^^^.
B.T.W, I am using this format to insert into mysql
$sql = mysql_query("INSERT INTO mixtapes (title, songs, posted_by_id, description, date)
VALUES('$mixtapetitle','$allmixtapetracks','$posted_by_id','$mixtapedescription', now())")
or die (mysql_error());
So in the end i want to pack all of the dynamic inputs into one single variable, each one separated by ^^^. The example below is how i want the variable $allmixtapetracks to look, so when I insert it, it looks EXACTLY like that.
Value of input 1^^^Value Of Input 2^^^Value of Input 3^^^Value of input 4^^^
EDIT:
This coding is causing my error. When the inputs are dynamicly created, the php $_POST ignores them. Why? I am not sure.
JavaScript:
<script type="text/javascript">
$(document).ready(function(){
var counter = 3;
$("#addButton").click(function () {
if(counter>40){
alert("The maximum allowed tracks is 40");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.html('<table><tr><td width="88"><label>Track #'+ counter + ' : </label></td><td><input size="32" class="mixtapetrack" type="text" id="track[]" name="track[]" ></td></tr></table>');
newTextBoxDiv.appendTo("#TextBoxesGroup").hide().show(50);
counter++;
});
$("#removeButton").click(function () {
if(counter==3){
alert("Your mixtape must contain at least two tracks!");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove().show().hide(40);
});
});
</script>
HTML:
<form action="add-mixtape.php" name="addmixtapeForm" class="addmixtapeForm" id="addmixtapeForm" autocomplete="off" method="post" enctype="multipart/form-data">
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<table>
<tr>
<td width="88"><label>Track #1: </label></td>
<td><input size="32" class="mixtapetrack" type="text" id="track[]" name="track[]" ></td>
</tr>
</table>
<table>
<tr>
<td width="88"><label>Track #2: </label></td>
<td><input size="32" class="mixtapetrack" type="text" id="track[]" name="track[]" ></td>
</tr>
</table>
</div>
</div>
<input type="button" value="Add Track" id="addButton" class="addREMOVEmixtapetrack">
<input type="button" value="Remove Track" id="removeButton" class="addREMOVEmixtapetrack">
</form>
$alltracks = implode('^^^', $_POST['track']) . '^^^';
Test code:
<?php
$alltracks = implode('^^^', $_POST['track']) . '^^^';
echo $alltracks;
?>
<form action="test.php" method="post">
<input size="32" class="mixtapetrack" type="text" id="track[]" name="track[]" >
<input size="32" class="mixtapetrack" type="text" id="track[]" name="track[]" >
<input size="32" class="mixtapetrack" type="text" id="track[]" name="track[]" >
<input size="32" class="mixtapetrack" type="text" id="track[]" name="track[]" >
<input type="submit">
</form>
I strongly recommend against storing multiple values in one column. The correct strategy is to create a normalized table which links mixtapes to tracks:
CREATE TABLE tapetracks (
mixtapeid INT NOT NULL,
trackname VARCHAR(256) NOT NULL
);
Then loop over the input values and insert each into the table:
$mixtapeid = <the current tape you are adding to>;
foreach ($_POST['track'] AS $track) {
$track = mysql_real_escape_string($track);
$result = mysql_query("INSERT INTO tapetracks (mixtapeid, trackname) VALUES ($mixtapeid, '$track')");
if (!$result) {
echo mysql_error();
break;
}
}
When storing multiple values in one column, you lose the ability to utilize a column index when querying, and it becomes a big hassle to query for individual values, requiring calls to REPLACE() and FIND_IN_SET() which may fail if the track names contain commas. It really is the wrong strategy.
Yes, sure you can:
$combined = "";
foreach ( $_POST['track'] as $t ){
$combined .= $t . "^^^";
}
$combined = substr(0,-3, combined) // only if you want to strip last 3 "^^^" symbols
This should do it....
I have no idea about how javascript works, but I was able to write the following code by copying from different sites.
My aim is to have 2 radio boxes (1 = India, 2 = Other than India) and if Other than India is selected, then a dropdown box is displayed which shows names of all countries.
The dropdown is selected from a database and it is achieved by a custom php function.
I am able to make the code display the dropdown based on my radio box selection.
What I am unable to do is as follows:
I am not able to select any values from the dropdown.
I'm not able to make the dropdown hide if I change the choice in the radio box
Here is the code of the form:
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<br />
<script type="text/javascript">
function onclickradio(entry){
if (entry === true) {
alert("YOU HAVE CHOSEN INDIA");
}
else {
document.getElementById('OTHER THAN INDIA').innerHTML = '</br><?php dropdown('country');?>';
}
}
</script>
Country: </br>
<input onclick="onclickradio(document.getElementById('INDIA').checked);" id="INDIA" name="country" type="radio" checked="checked"/> INDIA
<input onclick="onclickradio(document.getElementById('INDIA').checked);" id="OTHER THAN INDIA" name="country" type="radio"/> OTHER THAN INDIA
<br /><br /><br />
State: <input type="text" name="State" maxlength="30"/><br />
Line1: <input type="text" name="Line1" maxlength="50" /><br />
Line2: <input type="text" name="Line2" maxlength="50" /><br />
City: <input type="text" name="City" maxlength="40" /><br />
PIN Code: <input type="text" name="PIN_Code" maxlength="8" /><br />
<input type="submit" name="submit_address" value="Submit Address" />
</fieldset>
</form>
Here is the code for the custom PHP dropdown function:
<?php
function dropdown($tablename) /*remember to add single quote around the input*/
{
$sql="SELECT * FROM ".$tablename;
$result=mysqli_query($GLOBALS["connection"], $sql)
or die('Error in running SELECT query');
$options=""; //initialising the variable, so that it can be concatenated later
while ($row=mysqli_fetch_array($result))
{
$x=0; /*$x is the index of the field in a row (it has to start with $x=0;
because the first index is 0 in php*/
$rowstr=" # "; /*initialising the variable,
so that it can be concatenated later*/
while ($x+1<=mysqli_num_fields($result)) /*mysqli_num_fields gives the actual number of fields, and not the index.
Since the index starts with 0, it is to be incremented by 1
before comparison with the mysqli_num_fields*/
{
$rowstr.= $row[$x]." # "; //concatenation operator
$x=$x+1;
}
$options.="<option value=".$rowstr.">".$rowstr."</option>"; //concatenation operator
}
Echo "<select>".$options."</select>";
}
?>
A few things that come to mind:
Don't put spaces in id values. I recommend that you use lower case as well, so you could have "india" and "not-india" instead.
Use Firefox/Firebug or similar to see if you have any JavaScript errors when you run this
Consider using jQuery or similar to catch change events - it is easy to use and uses the 'unobtrusive' method of adding JS functionality to your page.
Id field of an element can not have space. Just try removing spaces in "OTHER THAN INDIA" or replace to looks like OTHER_THAN_INDIA
Try this:
$(document).ready(function() {
// hide address inputs
$('#address').hide();
// show address inputs if the not india button is pressed
$('#not-india').click(function() {
$('#address').show();
});
// re-hide address inputs if india is selected
$('#india').click(function() {
$('#address').hide();
});
});
You will also have to include jQuery in your page.
Fiddle: http://jsfiddle.net/EN4jB/6/
Please note that I used the following markup - particular attention is due to the id of this div.
<input id="india" name="country" type="radio" checked="checked"/> India
<input id="not-india" name="country" type="radio" /> Not India
<br />
<div id="address">
<p><select>
<option>USA</option>
<option>UK</option>
<option>Ireland</option>
<option>etc...</option>
</select>
</p>
<p>State: <input type="text" name="State" maxlength="30"/></p>
<p>Line1: <input type="text" name="Line1" maxlength="50" /></p>
<p>Line2: <input type="text" name="Line2" maxlength="50" /></p>
<p>City: <input type="text" name="City" maxlength="40" /></p>
</div>
To clear the selection if India is chosen
function onclickradio(entry) {
if(entry===true) {
alert("YOU HAVE CHOSEN INDIA");
document.getElementById('OTHER THAN INDIA').innerHTML = '';
}
else {
document.getElementById('OTHER THAN INDIA').innerHTML = '<br/><?php dropdown('country');?>';
}
}