form not working in php e-commerce wbsite - php

I'm trying to create an e commerce website for my semester project, but i cant seem to understand the problem with this code.I'm trying to take input from the admin regarding product name,image,details etc and then sending it to php code for processing and submitting it to the database,but the form isn't submitting anything.Here's the code:
<form action="inventory_list.php" method="post" name="f1" enctype="multipart/form-data">
Product Name:<input type="text" id="product_name" size="60" ><br>
Cost:<input type="text" size="10" id="product_cost" style="border:1px solid #c3c3c3;"><br>
Category:<select id="category" >
<option value="Watches">Watches</option>
<option values="Footwear">Footwear</option>
<option value="Apparels">Apparels</option>
</select><br>
Sub-Category:<select id="sub_category" >
<option value="Men">Men</option>
<option values="Women">Women</option>
</select><br>
Product Details:<textarea id="product_details"name="textarea" cols="60" rows="5" wrap="soft"></textarea><br>
Stock:<input type="text" size="10" id="stock" style="border:1px solid #c3c3c3;"><br>
Product Image:<input type="file" id="image"><br>
<input type="submit" id="submit" value="Add Item"><br>
</form>
and this my php code:
if(isset($_POST['product_name'])){
$product_name=mysql_real_escape_string($_POST['product_name']);
$product_cost=mysql_real_escape_string($_POST['product_cost']);
$category=mysql_real_escape_string($_POST['category']);
$sub_category=mysql_real_escape_string($_POST['sub_category']);
$product_details=mysql_real_escape_string($_POST['product_details']);
$stock=mysql_real_escape_string($_POST['stock']);
//Check if product already exists in the database
$sql=mysql_query("SELECT * FROM products WHERE product_name='$product_name'");
$row_count=mysql_num_rows($sql);
if($row_count>0){
echo 'Product already exists in the database,Back';
}else{
//Add this product to database
$sql2=mysql_query("INSERT INTO products (product_name, price, details, category, subcategory, stock, date_added) VALUES('$product_name','$product_cost', '$product_details', '$category', '$sub_category', '$stock', now())")or die(mysql_error());
$pid=mysql_insert_id($sql);
//UPload image to new folder
$newname="$pid.jpg";
move_uploaded_file($_FILES['image']['tmp_name'],"E:\Applications\Xampp\htdocs\The Store\Main\inventory_images/{$newname}");
header("location:inventory_list.php");
exit();
}
}
Any help is appreciated..

On your HTML form, each input needs a name as well as an id:
Product Name:<input type="text" id="product_name" size="60" ><br>
Should be:
Product Name:<input type="text" id="product_name" name="product_name" size="60" ><br/>
Every one of your inputs needs a name. The $_POST array derives from the input names, so they all need to match your PHP code as well. Also note #Loz Cherone's comment. Mysql functions are deprecated, and open you up to a variety of nasty attacks.

So Ive been going trough your project since there is nothing to do today at work and I noticed a couples of things.
First of all, like lars said, a POST use the name of the form to get his data, not the ID.
You also had some typos in your SELECT list where ''value'' where written ''values''.
So I change your code a little bit and you only have to make sure that you can connect to your DB and your set !
<form action="inventory_list.php" method="post" name="f1" enctype="multipart/form-data">
Product Name:<input type="text" name="product_name" size="60" ><br>
Cost:<input type="text" size="10" name="product_cost" style="border:1px solid #c3c3c3;"><br>
Category:<select name="category">
<option value="Watches">Watches</option>
<option value="Footwear">Footwear</option>
<option value="Apparels">Apparels</option>
</select><br>
Sub-Category:<select name="sub_category">
<option value="Men">Men</option>
<option value="Women">Women</option>
</select><br>
Product Details:<textarea name="product_details" cols="60" rows="5" wrap="soft"></textarea><br>
Stock:<input type="text" size="10" name="stock" style="border:1px solid #c3c3c3;"><br>
Product Image:<input type="file" name="image"><br>
<input type="submit" id="submit" value="Add Item"><br>
and your inventory_list.php
if(isset($_POST['product_name'])){
$product_name=mysql_real_escape_string($_POST['product_name']);
$product_cost=mysql_real_escape_string($_POST['product_cost']);
$category=$_POST['category'];
$sub_category=$_POST['sub_category'];
$product_details=mysql_real_escape_string($_POST['product_details']);
$stock=$_POST['stock'];
$sql=mysql_query("SELECT * FROM products WHERE product_name='$product_name'");
$row_count=mysql_num_rows($sql);
if($row_count>0){
echo 'Product already exists in the database,Back';
}else{
//Add this product to database
$sql2=mysql_query("INSERT INTO products (product_name, price, details, category, subcategory, stock, date_added) VALUES('$product_name','$product_cost', '$product_details', '$category', '$sub_category', '$stock', now())")or die(mysql_error());
$pid=mysql_insert_id($sql);
//UPload image to new folder
$newname="$pid.jpg";
move_uploaded_file($_FILES['image']['tmp_name'],"E:\Applications\Xampp\htdocs\The Store\Main\inventory_images/{$newname}");
header("location:inventory_list.php");
exit();
}
}
Hope it helps !

Related

Adding data to wordpress database using template

I decided to create my first Wordpress plugin, then I switched to create a template instead, because I had problems with sending the data through form action. Now I have problems with adding data to databse using a template. I have a problem with my functions.php file I think. Can someone help me, please? The code:
<?php
if(isset($_POST['submitbtn']))
{
global $wpdb;
$data_array = array(
'OrderNum' => $_POST['OrderNum'],
'OrderStatus' => $_POST['OrderStatus'],
'ClientFirstName' => $_POST['ClientFirstName'],
'ClientLastName' => $_POST['ClientLastName']
);
$table_name = 'ordernumber';
$sql=$wpdb->insert($table_name, $data_array, $format=NULL);
if($sql == 1){
echo '<h1>Added</h1>';
}else{
echo 'Error';
}
}
?>
EDIT:
For some reason I can't add my whole second php file here so here is just the form, and I want to add I am a beginner in this all. `
<form method = "post">
<fieldset>
<p><label for="ClientFirstName">First name:</label>
<input type="text" id="ClientFirstName" name="ClientFirstName"/>
</p>
<p><label for="ClientLastName">Last name:</label>
<input type="text" id="ClientLastName" name="ClientLastName"/>
</p>
<p><label for="OrderNum">Order number: </label>
<input type="text" id="OrderNum" name="OrderNum"/>
</p>
<p><label for="OrderStatus">Order status: </label>
<select name="OrderStatus" id="OrderStatus">
<option value="Your order is wating for">Your order is wating</option>
<option value="Order is shipped">Order is shipped.</option>
<option value="Done">Done</option>
<option value="Error in order">Error in order </option>
</select>
</p>
</fieldset>
<p><input type="submit" value="Add order" name="submitbtn"></p>
</form>`

How to update a forms text fields when a drop gets updated using php

I have a form in a php page that I want to have updated as the drop down is changed. Here is the code for the form:
<form action="AdminPage.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="action" value="version" />
<label><strong>Name:</strong></label>
<select id="WebName" name="Name">
<option value="ReportDashboard">ReportDashboard</option>
<option value="ReportDashboard Dev"<?php if(strpos($_SERVER['PHP_SELF'],"dev/FrontierReports",1) > 0){echo " selected='selected'";}?>>ReportDashboard Dev</option>
<option value="ReportDashboard Testing"<?php if(strpos($_SERVER['PHP_SELF'],"dev/Testing",1) > 0){echo " selected='selected'";}?>>ReportDashboard Testing</option>
</select><p></p>
<label><strong>Version Number: </strong></label>
<input id="VersionNumber" type="text" name="VersionNumber" value="<?php echo $VersionNumber['VersionNo']; ?>" /><p></p>
<label><strong>Version Type:</strong></label>
<select id="Type" name="VersionType">
<option value="1">Major</option>
<option value="2">Minor</option>
<option value="3" selected="selected">Bug</option>
</select><p></p>
<input type="hidden" name="VersionNumberCheck" value="<?php echo $VersionNumber['VersionNo']; ?>" />
<label><strong>Notes</strong></label>
<input id="Notes" type="text" name="Notes" value="<?php echo $ReleaseNotes['ReleaseNotes']; ?>" />
<p><input class="Pointer" type="submit" name="submit" value="Update Version" /></p>
<p><input id="VersionSubmit" class="Pointer" type="button" name="VersionSubmit" value="Current Notes" /></p>
</form>
Currently, the form gets its values for the 2 text fields (VersionNumber and Notes) from outside the form. I would like to have them be obtained as the form is created based on what the first drop down (Name) has selected and then update if that drop down gets changed.
I thought of adding some PHP to the form to help, but it doesn't work. Here is what I tried:
<form action="AdminPage.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="action" value="version" />
<label><strong>Name:</strong></label>
<select id="WebName" name="Name">
<option value="ReportDashboard">ReportDashboard</option>
<option value="ReportDashboard Dev"<?php if(strpos($_SERVER['PHP_SELF'],"dev/FrontierReports",1) > 0){echo " selected='selected'";}?>>ReportDashboard Dev</option>
<option value="ReportDashboard Testing"<?php if(strpos($_SERVER['PHP_SELF'],"dev/Testing",1) > 0){echo " selected='selected'";}?>>ReportDashboard Testing</option>
</select><p></p>
<?php
$Vsql = "select top 1 VersionNo,ReleaseNotes from pmdb.Version where Name = 'ReportDashboard' order by name,VersionNo desc";
$GetVersion = $conn->query($Vsql);
$VersionNumber = $GetVersion->fetch(PDO::FETCH_ASSOC);
?>
<label><strong>Version Number: </strong></label>
<input id="VersionNumber" type="text" name="VersionNumber" value="<?php echo $VersionNumber['VersionNo']; ?>" /><p></p>
<label><strong>Version Type:</strong></label>
<select id="Type" name="VersionType">
<option value="1">Major</option>
<option value="2">Minor</option>
<option value="3" selected="selected">Bug</option>
</select><p></p>
<input type="hidden" name="VersionNumberCheck" value="<?php echo $VersionNumber['VersionNo']; ?>" />
<label><strong>Notes</strong></label>
<input id="Notes" type="text" name="Notes" value="<?php echo $ReleaseNotes['ReleaseNotes']; ?>" />
<p><input class="Pointer" type="submit" name="submit" value="Update Version" /></p>
<p><input id="VersionSubmit" class="Pointer" type="button" name="VersionSubmit" value="Current Notes" /></p>
</form>
I don't know how to capture what is in the drop down to change the SQL that is pulling the data. I thought of possibly just pulling all of the rows back and then doing a search against it once the form is built, but I still don't know how to capture when the drop down changes and then update the 2 text boxes.
UPDATE
I now have a new file named UpdateAdminVersion.php this is what is has:
$Vsql = "select top 1 VersionNo,ReleaseNotes from pmdb.Version where Name = 'ReportDashboard' order by name,VersionNo desc";
$GetVersion = $conn->query($Vsql);
$VersionNumber = $GetVersion->fetch(PDO::FETCH_ASSOC);
$data = $VersionNumber;
echo json_encode($data);
I also added the following script to the previous file with the form:
$("#WebName").change(function ()
{
$.post("UpdateAdminVersion.php",
{
parameter1: "ReportDashboard Dev",
parameter2: $("#VersionNumber").val()
},
function (data, status)
{
aconsole.log(data)
$("#Notes").val(data);
});
});
I must still be missing something because nothing happens when I change the drop down.
UPDATE 2
I've changed the script to this:
$("#WebName").change(function ()
{
$.post("UpdateAdminVersion.php",
{
WebName: $('#WebName').val(),
VersionNumber: $("#VersionNumber").text()
},
function (data, status)
{
console.log(data)
$("#Notes").val(data);
success: alert ("Number 2 is successful!");
});
success: alert ("Number 1 is successful! \n" + WebName + "\n" + VersionNumber);
});
I get the alert Number 1 is successful!, but the WebName and VersionNumber variables return [object HTMLSelectElement] and [objectHTMLInputElement] respectively. How do I return the actual values?
And how do I use them in the UpdateAdminVersion.php file?
For starters you can use jqueryUI Autocomplete to feed Select tag with options.
Then use onchange event to capture dropdown changes.
<select onchange="myFunction()">
when event is triggered retreive data from db using Ajax, on success modify your form fields accordingly.
Look at this Fiddle give your own parameters, should work.

HTML Form Not POSTing? Has name field?

I feel like an absolute moron posting this question, but I'm completely serious, I officially have NO idea why this form isn't posting. I've gone from using AJAX to display information inputted to simple submit-redirect-grab Post data in PHP to $_SERVER["PHP_SELF"] trying to get the information to JUST POST, and it won't. Most of the people asking this question have had their answers revealed as "You need a name field" or "Your javascript is the issue" but I have a name field and I am no longer using javascript. I am utterly and completely confused.
For reference, I'm using PHPStorm and a Local server to test this out. I just logged on fresh today, saved the project, ran it for the first times today, made sure it wasn't just a sort of cached project, and it doesn't appear to have anything with old data.
Please don't mind if some of the form syntax is messy, I just want this darn post to work so I can move on to the meat of what I'm trying to make. Also there is no stylesheet currently, it's mostly empty apart from
.id {
height: 100px;
}
Also none of the form fields are required, you really only need to enter information into one. I've got it doing a var_dump just so I can see all of the form post data, and it's brilliantly not working. I did have it echoing out something in PHP along the lines of "Done!" to show php is being read, and I also had it attempting to echo $_POST["modelnumber"] just to see that. Nope.
index.php
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="index.css">
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Model Number:<br>
<input type="text" id="mod" name="modelnumber"><br><br>
Amazon Item?<br>
<input type="radio" id="amazonItemY" name="amazonItem" value="yes"> Yes<br>
<input type="radio" id="amazonItemN" name="amazonItem" value="no" checked> No<br><br>
Item name:<br>
<input type="text" id="intName" name="itemName"><br><br>
Item Description:<br>
<input type="text" id="internetDescription" name="description"><br><br>
Brand:<br>
<input type="text" id="brand" name="itemBrand"><br><br>
Manufacturer:<br>
<input type="text" id="manufacturer" name="manName"><br><br>
Website category:<br>
<input type="text" id="cmcategory" name="category"><br><br>
Clearance?<br>
<input type="radio" id="clearanceY" name="clearance" value="yes"> Yes<br>
<input type="radio" id="clearanceN" name="clearance" value="no" checked> No<br><br>
Competitor Price: (leave empty if not clearance)<br>
<input type="text" id="competitorPrice" name="compPrice"><br><br>
School price:<br>
<input type="text" id="catStdPrice" name="schoolPrice"><br><br>
Dealer price:<br>
<input type="text" id="dealerStdPrice" name="dealerPrice"><br><br>
Website price(normal):<br>
<input type="text" id="intCsiPrice" name="webPrice"><br><br>
Unit of Measure:<br>
<input type="text" id="unitOfMeasure" name="uom"><br><br>
UPC:<br>
<input type="text" id="upc" name="upcNum"><br><br>
Manufacturer Part Number:<br>
<input type="text" id="mfgr_num" name="manfacNum"><br><br>
Item Attribute:<br> <!--needs to be a dropdown-->
<select id="attribute" name="attributes">
<option value="(1593325)Baseball">Baseball</option>
<option value="(1593326)Basketball">Basketball</option>
<option value="(1593386)Boating + Paddling">Boating + Paddling</option>
<option value="(1593314)Camping Hiking + Climbing">Camping_ Hiking + Climbing</option>
<option value="(1610848)Cricket">Cricket</option>
<option value="(1593313)Cycling">Cycling</option>
<option value="(1593315)Equestrian">Equestrian</option>
<option value="(1593318)Fishing">Fishing</option>
<option value="(1593323)Football">Football</option>
<option value="(1594100)General Sports Equipment + Accessories">General Sports Equipment + Accessories</option>
<option value="(1593320)Golf">Golf</option>
<option value="(1593319)Hunting + Archery">Hunting + Archery</option>
<option value="(1593329)Ice + Roller Hockey">Ice + Roller Hockey</option>
<option value="(1593327)Other Sports">Other Sports</option>
<option value="(1593331)Personal Fitness">Personal Fitness</option>
<option value="(1599122)Pool + Billiards">Pool + Billiards</option>
<option value="(1593321)Rugby">Rugby</option>
<option value="(1593317)Skateboarding + Rollerskating">Skateboarding + Rollerskating</option>
<option value="(1593330)Ski + Snow">Ski + Snow</option>
<option value="(1593322)Soccer">Soccer</option>
<option value="(1593324)Softball">Softball</option>
<option value="(1593316)Tennis">Tennis</option>
<option value="(1593328)Water Sports">Water Sports</option>
</select><br/>
<input type="submit">
</form>
<?php
var_dump($_POST);
?>
RedRazor's answer is not a solution. The PHP interpreter resets the quotes inside of the php tags. This means that you can re-use the same quotes in the interpretation snippet.
This seems more like a PHP Storm issue, try to restart your PHP Storm server. I copied your code exactly to my machine and used PHP Storm built in server. With no modifications your code worked. I've attached some images of my setup.
Also you have to be running the PHP server to get $_POST requests, there is an icon to just open in the browser, which will work for many cases, but it will not work on requests like this due to their nature.
Here are some images of my setup:
Please make sure that there is no conflict between quotation marks ("")
Instead of
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Try
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">

How do I determine which dynamically-generated submit button was clicked in my PHP form?

I want to edit a dynamically-generated form (meaning: I don't know how many rows will be generated). This content is generated within a while loop, and the HTML generated has creates buttons of input-type=submit, generating as many identically-named buttons as there are iterations in the loop.
Of the generated buttons, I want to know which submit button has been clicked, in order to provide the user the same form for which it has been clicked. Disregard the name of the database and password to connect it; the connectivity is fine.
Feel free to suggest any new method to achieve the desired functionality.
The code is as follows:
echo "you have reached your travel details page. your recent travelling details are as follows".'</br>';
$dbc=mysqli_connect('localhost','xyz','xyz','abc') or die("connection to DB failed");
$query="SELECT * FROM travel_details WHERE emailid='{$_SESSION['username']}' ORDER BY dep_date DESC";
$result=mysqli_query($dbc,$query) or die("error in querying the DB");
?>
<h1>Your travel details are:-</h1>
<form name="showtraveldet" METHOD="POST" action="edittraveldet.php">
<table border="1">
<tr>
<th>Starting point</th><th>Ending point</th><th>No of passengers</th><th>Expected fare</th><th>Departure date</th>
<th>Departure time</th><th>Arrival Date</th><th>Arrival Time</th><th>Car Model</th><th>Car number</th>
<th>Who is driving</th><th>Driver's license number</th>
</tr>
<?php
while ($row=mysqli_fetch_array($result))
{
$tid=$row['travel_id'];
echo "the value of tid is '{$tid}'";
echo'<tr><td>'.$row['start_point'].'</td><td>'.$row['end_point'].'</td><td>'.$row['no_of_pass'].'</td><td>'.
$row['exp_fare'].'</td><td>'.$row['dep_date'].'</td><td>'.$row['dep_time'].'</td><td>'.$row['arr_date'].'</td><td>'.$row['arr_time'].'
</td><td>'.$row['car_model'].'</td><td>'.$row['car_no'].'</td><td>'.$row['who_is_driving'].'</td><td>'.$row['driver_license_no'].'</td>
<td><input type="submit" name="edit" value="Edit"></td></tr><input type="hidden" name="travelid" value="'.$row['travel_id'].' ;?>">';
}
edittraveldet.php :-
$travelid=$_POST['travelid'];
echo "the travel id in the variable is $travelid and got the value from '{$_POST['travelid']}'";
$dbc=mysqli_connect('localhost','xyz','xyz','abc') or die("connection to DB failed");
$query="SELECT * FROM travel_details WHERE travel_id='{$travelid}'";
$result=mysqli_query($dbc,$query) or die("error in querying the DB");
mysqli_close($dbc);
$row=mysqli_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return validatewheregoing()" name="wheregoing">
<h1> Enter your travelling details so that other travellers can join you</h1>
<fieldset>
<legend> Travelling details </legend>
Start Point: <input type="text" name="start" value="<?php echo $row['start_point']; ?>"/><br />
End point: <input type="text" name="end" value="<?php echo $row['end_point']; ?>"/><br />
Passengers allowed: <input type="number" name="noofpass" value="<?php echo $row['no_of_pass']; ?>"/><br />
Expected Fare per passengers in rupees:<input type="number" name="fare" value="<?php echo $row['exp_fare']; ?>"/><br />
Departure Date:<input type="date" name="depdate" value="<?php echo $row['dep_date']; ?>"/><br/>
Departure time:<input type="time" name="deptime" value="<?php echo $row['dep_time'] ;?>"/><br/>
Arrival Date:<input type="date" name="arrdate" value="<?php echo $row['arr_date']; ?>"/><br/>
Arrival time at destination:<input type="time" name="arrtime" value="<?php echo $row['arr_time']; ?>"/><br/>
Car Model and name:<input type="text" name="cardet" value="<?php echo $row['car_det']; ?>"/><br/> <!--make this as a dropdown box for better database matching-->
Car Number:<input type="text" name="carno" /><br/><input type="checkbox" name="taxi" value="check this box if pooling a taxi">
Is the car self driven or driven by driver?<input type="radio" name="drivedet" value="Selfdriven" checked=""/>Self Driven<input type="radio" name="drivedet" value="driverdriven" />Driver driven<br />
Driver's License number<input type="text" name="licence_no"/></br>
<input type="checkbox" name="taxi" value="check this box if pooling a taxi"></br>
<input type="hidden" name="travelid" value="<?php echo $travelid ;?>" />
<input type="submit" value="invite travellers" name="editwheregoing"/>
</fieldset>
</form>
If only you can change your code, I would suggest you put the form tag itself in the while loop, each having the same action pointing to the same url but submitting different information to the destination page. This way you don't have to worry about the button clicked
while($row=mysqli_fetch_array($result))
{
//<form action="sameactionurl.php" name="form_1">
//<input type="hidden" name="travelid" value="$row['travelid']" />
//</form>
}
Another solution, if you don't want to change your code is use JavaScript to set a common hidden field to the value of the current ID before submitting the form
Name your submit buttons in a standard fashion and append a 3-digit number to the end, "button_XXXX_###" where ### is the number and XXX was the original name of your button.
After submission, check your request parameters for all variables starting with name "button_XXXX", and split the actual name "button_XXXX_####" by '_' character, and the "###" suffix will reveal the number of the button pressed.
It might be easier to create a form for each row instead, though.

PHP code inside javascript

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');?>';
}
}

Categories