I'm retaining values in form elements after a form submit. I've got it to work fine with a select box using the following:
<select name="BranchManager" class="formfield" id="BranchManager"onchange="document.forms[0].submit();SEinit();"><option value="">-- Select Manager --</option>
<?php
$area = $_POST['Area'];
if ($area); {
$BMquery = "SELECT DISTINCT Branch_Manager FROM Sales_Execs WHERE AREA = '$area' ".
"ORDER BY Branch_Manager";
$BMresult = mysql_query($BMquery);
while($row = mysql_fetch_array($BMresult))
{
echo "<option value=\"".$row['Branch_Manager']."\">".$row['Branch_Manager']."</option>\n ";
}
}
$branchmanager = $POST['BranchManager'];
?>
<script type="text/javascript">
document.getElementById('BranchManager').value = <?php echo json_encode(trim($_POST['BranchManager']));?>;
</script>
Which works fine (apologies if it isn't the cleanest/most efficient code, I'm doing my best!) The next field is a text field that needs to be populated based off the Branch Managers name above. So I've used :
<input name="BranchNum" type="text" class="formfield" id="BranchNum" size="3" maxlength="3" />
<?php
$bm = $_POST['BranchManager'];
if ($bm); {
$BNumquery = "SELECT DISTINCT BRANCH_NUM FROM Sales_Execs WHERE Branch_Manager = '$bm' ";
$BNumresult = mysql_query($BNumquery);
}
$branchnum = $POST['BranchNum'];
?>
<script type="text/javascript">
document.getElementById('BranchNum').value = <?php echo json_encode($BNumresult);?>;
</script>
Which isn't working... where am I going wrong here?
why are you having semicolons after if condition checks?
if ($bm);
if ($area);
This will always terminate the statement and whatever is in the curly braces will always get executed irrespective of the value in $bm or $area
You need mydql_fetch functions to retrive data from $result.
if($row = mysql_fetch_array($BNumresult))
$branchNum = $row[BRANCH_NUM];
why are you using json_encode when your input tag has size = 3?
You need to put value="<? echo $variableName; ?>" inside the input field
The reason is because a) you're not echoing, and b) you must echo in a different spot than in a select. You must echo in the value portion of the input.
<?php
$bm = mysql_real_escape_string($_POST['BranchManager']);
if ($bm) {
$BNumquery = "SELECT DISTINCT BRANCH_NUM FROM Sales_Execs WHERE Branch_Manager = '$bm' ";
$BNumresult = mysql_query($BNumquery);
}
$branchnum = $POST['BranchNum'];
?>
<input name="BranchNum"
type="text"
class="formfield"
id="BranchNum"
size="3"
maxlength="3"
value="<?php echo htmlspecialchars($branchnum); ?>" />
As per the comments, they are correct; you should not be using mysql_*. Instead, look at PDO; though this is outside the scope of your question.
Related
This is a dynamic dropdown in PHP/mySQL.
I want to store the name in the database server but the tag outputs the integer value.
If i change the code from <option value="<?php echo $row["id"]; ?>"> to <option value="<?php echo $row["name"]; ?>"> It shows my_sqli_fetch_array expects parameter 1 error.
My objective being to store the corresponding $row["name"] that is being displayed on the dropdown instead of $row["id"].
<?php
$link = mysqli_connect("localhost","root", "");
mysqli_select_db($link,"loginsystem");
?>
<form name="form1" action="" method="post">
<table>
<tr>
<td>Select Assembly Line</td>
<td><select id ="assemblylinedd" onChange="change_assemblyline()">
<option>Select</option>
<?php
$i=1;
$res=mysqli_query($link, "SELECT * FROM assemblyline");
$count=mysqli_num_rows($res);
if ($count >0){
while($row=mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
}
<?php $i++;} }else{
echo "No record Found !";
} ?>
</select></td>
</tr>
Scripting code :
<script type="text/javascript">
function change_assemblyline()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?assemblyline="+document.getElementById("assemblylinedd").value, false);
xmlhttp.send(null);
alert(xmlhttp.responseText);
document.getElementById("devices").innerHTML=xmlhttp.responseText;
}
This is my ajax.php
$link = mysqli_connect("localhost","root", "");
mysqli_select_db($link,"loginsystem");
$assemblyline = isset($_GET['assemblyline']) ? $_GET['assemblyline'] : '';
$devices = isset($_GET['devices']) ? $_GET['devices'] : '';
if($assemblyline!="")
{
$res=mysqli_query($link, "SELECT * FROM devices WHERE devices_id=$assemblyline");
echo "<select id='devicesdd' onchange='change_devices()'>";
while($row=mysqli_fetch_array($res))
{
echo "<option value='$row[id]'>";echo $row["name"]; echo "</option>";
}
echo "</select>";
}
Please do ignore onchange_devices() as it follows the same for next consecutive dropdown.
Though, its your requirement to save device name in DB, it is advised to save numeric id.
Reason: Name may change, but, id will persist.
If say your device id:name is 99 : iPhone 6 and you save in DB: iPhone 6, later the name gets changed to iPhone6.
In this scenario if you search records with name iPhone6, clearly, your above record will not show.
If you save numeric id, it will show irrespective of name change.
Coming back to your question:
I cannot write code here. But a pseudo code logic will help (hope so):
Take a hidden field device_name.
On change of drop down, with jQuery, assign value to hidden field.
$("#assemblylinedd option:selected").text();
Now, after submit, you will get device_name in hidden field.
$devices = isset($_GET['device_name']) ? $_GET['device_name'] : '';
Save this to DB.
$link = mysqli_connect("localhost","root", "");
mysqli_select_db($link, "loginsystem");
$assemblyline = isset($_GET['assemblyline']) ? $_GET['assemblyline'] : '';
$devices = isset($_GET['devices']) ? $_GET['devices'] : '';
if(!empty(trim($assemblyline)))
{
$res = mysqli_query($link, "SELECT * FROM devices WHERE devices_id = '$assemblyline'");
echo "<select id='devicesdd' onchange='change_devices()'>";
while($row = mysqli_fetch_array($res))
{
echo "<option value='" . $row["id"] . "'>" . $row["name"] . "</option>";
}
echo "</select>";
}
I've added a proper empty check instead of your != "", which didn't previously prevent a single space from being passed.
I've quoted your query value, I would definitely use prepared statements instead of passing values directly.
I've quoted your $row[id].
I've concatenated your string correctly.
Note: It would be preferable to return a JSON array object with the IDs and the names instead of outputting HTML via the AJAX, it would make your code-base much cleaner and adaptable in the future.
Reading Material
empty
trim
Perhaps there may be an easier way to do this however, I need the project to select a patient from the drop down menu. Then when the dropdown menu has got a value, the text field needs to take the NHS number from that drop down menu (array) so that it can be posted elsewhere.
<select name="patient" class="textbox" required>
<option value="">Select a patient</option>
<?php
include 'dbconnection.php';
$sql = "SELECT * FROM clients ORDER by firstname ASC";
$result = mysqli_query($conn, $sql);
$result = $conn-> query($sql);
while($row=mysqli_fetch_array($result))
{
?>
<option value="<?php echo $row["firstname"]." ".$row["lastname"]; ?>">
<?php echo $row["firstname"]." ".$row["lastname"] .", ".$row["addressl1"].", ".$row["addressl2"].", ".$row["county"].", ".$row["postcode"].", ".$row["nhsnum"]; ?></option>
<?php
$nhs = $row['nhsnum'];
}
?>
</select>
<?php
$sql = "SELECT * FROM clients WHERE nhsnum = $nhs ";
$result = mysqli_query($conn, $sql);
$result = $conn-> query($sql);
while($row=mysqli_fetch_array($result))
{
?>
<input type="text" placeholder="NHS number" readonly value=" <?php echo $row["nhsnum"]; ?>">
<?php
}
?>
As you may see, I have created dummy variables of $nhs however its a static variable and doesnt change upon user selection from the drop down list. Can anyone explain how I can merge the two together.
DB setup
i think you should declare the $nhs outside the while loop
Use AJAX, as already suggested, or a form submit button. Your second query should be where your AJAX or submitted form goes. Use $_GET or $_POST, if you are using get or post method, to intercept the option value. Assign that value to your $nhs, then use as you have.
Set the option value to the $nhs value you want, not the person’s name. Example using $_POST
if(isset($_POST['patient'])){
$nhs=$_POST['patient'];
}else{
// whatever code you want to handle a non-submitted value.
}
Add additional code to prevent SQL injection.
I tried to build an admin page. The admin will fill a form to add new product in the database and display it in the shop website. The problem is when I tried to select a gender from the dropbox, the new product doesn't add in the product table in the database as you can see below: (I want to select gender such as Boys)
The Admin Page and database result:
The code I used:
$host = "";
$userMS = "";
$passwordMS = "";
$connection = mysql_connect($host,$userMS,$passwordMS) or die("Couldn't connect:".mysql_error());
$database = "projectDataBase";
$db = mysql_select_db($database,$connection) or die("Couldn't select database");
if (isset($_POST['sAddProduct']))
{
addNewProduct();
}else if(isset($_POST['delete']))
{
$Product_ID=$_POST['Product_ID'];
$mysqlquery="delete from Product where Product_ID= ".$Product_ID."";
mysql_query($mysqlquery);
echo "Deleted successfully";
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}else{
showForm();
}
// add new product
function addNewProduct()
{
$ProductName = $_POST['Product_Name'];
$ProductPrice = $_POST['Price'];
$Gender = $_POST['Gender_ID'];
//database query to add product
$insertStringProduct = "INSERT into Product(Product_Name, Price,Gender_ID)
VALUE('$ProductName', '$ProductPrice', '$Gender')";
$result = mysql_query($insertStringProduct);
echo ("<p1>Product added Successfully</p1>");
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}
//function for the form page
function showForm()
{
//First form for adding new product
$self = htmlentities($_SERVER['PHP_SELF']);
echo("<form action = '$self' method='POST'>
<fieldset>
<legend>Adding New Product</legend>
Product Name: <input name='Product_Name' type='text' size = '40'>
<br /><br />
Price: <input name='Price' type='text' size = '20'><br><br />
Gender:
<select name='Gender_Description'>
<option value = '%'> <-- select--></option>");
$dbQuary = " SELECT DISTINCT Gender_Description from Gender";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[0]</option>");
}
echo("
</select>
<br/><br/>
<input type='submit' name='sAddProduct' value = 'Add'/>
<input type='reset' value='Clear' />
</fieldset>
</form>");
}
The result ( nothing added)
However, when I change the code to
Gender:
<select name='Gender_ID'>
<option value = '%'> <-- select--></option>");
$dbQuary = " SELECT DISTINCT Gender_ID from Gender";
$result = mysql_query($dbQuary);
It's working
Can anyone help me with this?
In addNewProduct you are expecting $_POST['Gender_ID'] to be set. So of course, <select name='Gender_Description'> would not work, because Gender_Description != Gender_ID. That's also why it does work when you change it.
I'm assuming what you want to achive is to display the gender description, and it still to work. For that, you need both the id and the description:
$dbQuary = " SELECT DISTINCT Gender_ID, Gender_Description from Gender";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[1]</option>");
}
Security
Your code is extremely unsafe. You are using mysql_* which is deprecated since 2013, and you are not sanitizing the input in any way, so your code is open to SQL injection (which is possibly in all kinds of queries; insert, update, delete, etc, and allows for data leaks, DOS, and possibly code execution and deletion/changing of data). The preferred way to prevent this are prepared statements (either using mysqli_* or PDO). They are not difficult to use, and the resulting code is also nicer.
You are not concatenating values as it should
Change
echo("<option value ='$row[0]'> $row[0]</option>");
to
echo("<option value =". '$row[0]' . "> ". $row[0]. "</option>");
OR
echo("<option value ='{$row[0]}'> {$row[0]}</option>");
EDIT:
Change your While-loop
while($row = mysql_fetch_array($result,MYSQL_BOTH)) {
echo("<option value ='{$row['gender_id']}'> {$row['gender_description']}</option>");
}
This will generate a Select list showing the Gender Description and and values will be numeric(of database)
I have a HTML dropdown list populated by PHP as following:
<form name="selectOccupation" method="post" action="specific_occupation.php">
<div align="centre">
<select name="occupation_dropdown" id="occupation_dropdown">
<?php
include "connection.php";
$sql = mysql_query("SELECT DISTINCT Occupation from patient_info");
while ($row = mysql_fetch_array($sql)) {
echo "<option value=".$row['Occupation'].">".$row['Occupation']."</option>";
}
?>
</select>
</div>
<br>
<br>
<input type="submit" name="submit" value="Proceed"/>
</form>
In the specific_occupation.php file, I have this code:
<?php
include "connection.php";
$selectedoccupation = $_POST['occupation_dropdown'];
echo $selectedoccupation;
$myquery = "SELECT patient_info.Name, test_info.DateOfTest FROM `patient_info`,`test_info` WHERE patient_info.PatientID = test_info.PatientID AND patient_info.Occupation = '$selectedoccupation' ";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
$tempdata = json_encode($data);
?>
This works fine if an occupation without any white space between them like "carpenter" is selected from the dropdown menu but doesn't work for "sales person". How can the $_POST be used for occupations with white spaces??
Thanks in advance !!
You're building your HTML wrong. You've got it as:
<option value=Sales Person>
^^^^^---what will get sent as the value
^^^^^^---some wonky unknown/non-standard attribute
This is incorrect. HTML now requires that ALL attributes be quoted:
<option value="Sales Person">
and even when the quotes weren't required, you still had to have the quotes to handle "spaced" data like this.
PHP post replace some characters such as - with whitespaces.
You can try urlencode($var) in your PHP script.
I have gone through various posts but can't find a solution to this problem:
I have a form with several rows of fields to insert in a database table with one Click of the submit button. This is the code of the HTML:
<form action="filename.php?cartID=<?php echo $_GET['cartID'];?>&customer_id=<?php echo $_GET['customer_id'];?>&total_count=<?php echo $_GET['total_count'];?>&action=add" method="post" id="add_participants" >
<table>
<?php for ($i=0, $n=$_GET['total_count']; $i<$n; $i++) { ?>
<input type="hidden" name="customer_id[]" id="customer_id[]" value="<?php echo $_GET['customer_id'];?>" />
<input type="hidden" name="cartID[]" id="cartID[]" value="<?php echo $_GET['cartID'];?>" />
<input type="hidden" name="products_id[]" id="products_id[]" value="<?php echo $_GET['products_id'];?>" />
<tr><td><label for="title[]">Title</label></td><td><select id="title[]" name="title[]">
<option value="Dr">Dr</option>
<option value="Miss">Miss</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Prof">Prof</option>
</select>
</td>
<td><label for="firstname[]">First Name</label></td><td><input type="text" id="firstname[]" name="firstname[]"/></td>
<td><label for="surname[]">Surname</label></td><td><input type="text" id="surnam[]e" name="surname[]"/></td>
<td><label for="email[]">E-mail</label></td><td><input type="text" id="email[]" name="email[]"/></td></tr>
</table>
<?php } ?>
<input value="Add participant" type="submit" />
On the action page the code is the following:
for ($i=0, $n=$_GET['total_count']; $i<$n; $i++) {
$title[$i] = tep_db_prepare_input($HTTP_POST_VARS['title.$i]']);
$firstname =tep_db_prepare_input($HTTP_POST_VARS['firstname.$i']);
$surname =tep_db_prepare_input($HTTP_POST_VARS['surname.$i']);
$email = tep_db_prepare_input($HTTP_POST_VARS['email.$i']);
$customer_id = tep_db_prepare_input($HTTP_POST_VARS['customer_id.$i']);
$cart_id = tep_db_prepare_input($HTTP_POST_VARS['cartID.$i']);
$products_id = tep_db_prepare_input($HTTP_POST_VARS['products_id.$i']);
$query = "INSERT INTO participants (title,Firstname,Surname,Email,customers_id,cart_id,products_id) VALUES ('$title[$i]', '$firstname[$i]', '$surname[$i]', '$email[$i]', $customers_id[$i], $cart_id[$i], $products[$i])";
echo $query . "<br />";
mysql_query($query) or die(mysql_error());
}
However, I cannot get the values of the $_POST variables into the variable arrays to use in the insert statement.
Can anyone help me with this please? I have tried different permutations of the code, and I'm still not getting anywhere.
Many thanks.
I'm fairly certain that $HTTP_POST_VARS is deprecated.. you should be using $_POST instead.
Secondly, your processing doesn't really need to loop over a for loop. You could use foreach to loop over all posted values instead.
Example (untested):
foreach($_POST['customer_id'] as $key => $customerID) {
$title = !empty($_POST['title'][$key]) ? $_POST['title'][$key] : "";
$firstName = !empty($_POST['firstname'][$key]) ? $_POST['firstname'][$key] : "";
// etc...
}
if your keeping the loop the same way, you need to make a change to how you refer to your array elements. change $title[$i] = tep_db_prepare_input($HTTP_POST_VARS['title.$i]']); to
$title[$i] = tep_db_prepare_input($_POST['title'][$i]);
and change the rest of your assignments to follow the same pattern.
The output of tep_db_prepare_input() is of course a mistery, but apart from that it's true what Marc B. says: "Learn basic PHP syntax rules"
$query = "INSERT INTO participants (title,Firstname,Surname,Email,customers_id,cart_id,products_id) VALUES ('$title[$i]', '$firstname[$i]', '$surname[$i]', '$email[$i]', $customers_id[$i], $cart_id[$i], $products[$i])";
echo $query . "";
This will output exactly what's between the double quotes. Try using:
$query = "INSERT INTO participants (title,Firstname,Surname,Email,customers_id,cart_id,products_id) VALUES ('".$title[$i]."', '".$firstname[$i]."', '".$surname[$i]."', '".$email[$i]."', ".$customers_id[$i].", ".$cart_id[$i].", ".$products[$i].")";
echo $query . "";
Using "{$array[$key]}" within double quotes also works, but using "$array[$key]" within double quotes does not work.
Further, $HTTP_POST_VARS is deprecated. Use $_POST
Your code has multiple errors that result in unintended values:
$title[$i] = tep_db_prepare_input($HTTP_POST_VARS['title.$i]'])
foreach is definitely clearer than a for loop
What others said: $HTTP_POST_VARS must be $_POST (or $_REQUEST)
Assuming that your mysterious tep_db_prepare_input() functions correctly, $HTTP_POST_VARS['title.$i]'] is syntactically incorrect. Single quotes mean variables are not parsed: your function is passed the (invalid) contents of $_POST['title.$i]']. I believe you meant to write $POST["title$i"] (where the "." is part of the field name. (Personally an underscore would be less confusing as "." has meaning in PHP.)
So... fix all that and you should be good to go. Well, #2 & 3, at least.