PHP drop down selection - php

I've set up a php form that registers a project to our database, it has a drop down that populates from our customer/supplier databases.
I've also set up a function to edit these projects, the problem I have is that when I go to my edit page it just displays the customer/supplier name and not in the drop down but a value box - is there a way to have the edit page display the dropdown but also be selected on the original supplier/customer?
Register project page
<?php
$result = mysql_query('SELECT name FROM customers ORDER BY name ASC');
echo '<select name='client'>';
while($row = mysql_fetch_assoc($result))
{ `
echo '<option value = ''.$row[name].''>'.$row[name].'</option>';
}`
echo '</select>';
?>
Edit page
<input type='text' name='client' value='<?php echo $client; ?>'/>
I tried a few tutorials and code tweaks but kept getting errors. I am aware of my sql injection problem, at the moment this site is internal.
Any help would be appreciated.
thanks

instead of $row[name] you should use $row['name']
$client= "<select name='client'>"; // you had error here also.
while($row = mysql_fetch_assoc($result))
{
$client.= "<option value = '".$row['name']."'>'".$row['name'].'</option>';
}
$client.= '</select>';
now echo $client to get dropdown.no need of constructing separate select tag now.
for selected use like this:
$client1= "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
if($row['name'] == $clientValue){
$client.= "<option selected='selected' value = '".$row['name']."'>'".$row['name'].'</option>';
}else{
$client1.= "<option value = '".$row['name']."'>'".$row['name'].'</option>';
}
}
$client1.= '</select>';
on echo of $client1 you will get selected based on the value $clientValue which you have to pass.

On your edit page:
<?php
$result = mysql_query('SELECT name FROM customers ORDER BY name ASC');
echo "<select name=\"customer\">";
while($row = mysql_fetch_assoc($result))
{
if ($row['name'] == $client)
{
echo "<option selected value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
}
else
{
echo "<option value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
}
}
echo "</select>";
?>

I also suggest that you change the old extension for mysql. I can't see no SQL Injection problem for now, but you should take care of it even if it is internal, because, from different reasons you will forget to sanitize it later. If you are writing it, then write it correctly.
Now for the problem, you are not using the quotes correctly, hence the errors. Do not use the same type of quotes, but change them, like so:
echo '<select name="client">';
Or if you use double quotes for concatenation, use single inside.
In case you have to use the same, escape them with \

For starters, you have a syntax error here:
echo '<select name='client'>';
(There are probably more quoting errors throughout the code, but I digress...)
As for using a drop-down, what you're looking for is the selected attribute. When you're building the page elements to display the form on the "edit" page, presumably you have the values that you're looking to display. When your loop finds an element which matches the value, select it:
while($row = mysql_fetch_assoc($result))
{
if ($knownValue == $row[name]) {
echo '<option selected value = ''.$row["name"].''>'.$row["name"].'</option>';
} else {
echo '<option value = ''.$row["name"].''>'.$row["name"].'</option>';
}
}

Related

Get value from a dropdown list and insert it in the database

Hello I have a drop down list with options that a get from a table in my database and I want when the user select on of the options to store it in another table of the database. I have the code for the select by a cant find the way to get the correct value in order to store.
Here is the code for the drop down list ...
<select id="SelectDisease" name="disease">
<?php
$sql = mysql_query("SELECT name FROM disease");
while ($row = mysql_fetch_array($sql))
{
echo "<option value=$disease>" . $row['name'] . "</option>";
}
?>
</select>
And here is the insert into code ...
queryMysql("INSERT INTO patient (fname,lname,username,email,password,gender,age,disease,spid) VALUES('$fname','$lname','$username','$email', '$password','$PatientG','$PatientAge','$disease','$PatientSPID')");
die("<h4>Account created</h4>Please Log in.<br /><br />");
I'm not sure if I understand your question correctly, but here is a method:
Include the <select/> tag within a <form/> tag with an action to another PHP page.
In the second PHP page, read the variable out $disease = $_POST['disease']
Call your SQL Insert Statement
Side Note:
Perhaps change:
echo "<option value=$disease>" . $row['name'] . "</option>";
to
echo "<option value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
Is this helpful?
This is a bit of a mess, so this might be a messy post, but I'll try to clarify what I think you're trying to do. For your select input:
<select id="SelectDisease" name="disease">
<?php
$sql = mysql_query("SELECT name FROM disease");
while ($row = mysql_fetch_array($sql)){
echo "<option value='".$row['name']."'>".$row['name']."</option>";
}
?>
</select>
That way, your select's options each have a different value, and not $disease, whatever that equated to.
Next, where you process your POST request:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
... // Etc for each input you have.
$disease = $_POST['disease'];
Then your query should work correctly:
queryMysql("INSERT INTO patient
(fname,lname,username,email,password,gender,age,disease,spid)
VALUES('$fname','$lname','$username','$email', '$password','$PatientG','$PatientAge','$disease','$PatientSPID')");
If that doesn't work, comment with any errors and we'll try to sort them out.
NOTE
This is INCREDIBLY insecure. I would never recommend doing this on a live application, as SQL Injections would be quite easy. Also, please note that MySQL functions are being deprecated. Look up MySQLi or PDO and learn to implement those.
Best of luck.

How to prevent echoing same value twice in php

So I have this drop down list in my form which pull "tags" from database as value for drop down options:
<select name="cartags">
<?php $result = mysql_query("SELECT * FROM Products WHERE ID > '0'");
while($row = mysql_fetch_array($result))
{
echo "<option value=\""; echo $row['Tag']; echo "\""; echo ">"; echo $row['Tag']; echo "</option>";
}
?>
</select>
What is my problem? My problem is that I am adding a lot of products into my databas and my code make dropdown list with tags for all this producst even if they have same tag. So what I need is solution how to prevent that same tag appear twice in my drop down.
I am pretty new to PHP and this is my first question here so I really hope that I explained my problem well.
Thanks in advance!
What is the purpose of WHERE ID > '0'? If ID is an auto-increment then it will always be positive. If not, it should be.
Why are you using mysql_fetch_array and then only using the associative keys? You should use mysql_fetch_assoc instead.
Why are you using a new echo every time you want to output a variable? Just concatenate.
Why are you setting the same string in value as the option's text? Without a value, it defaults to the text anyway.
Why are you not using backticks around your column and table names?
Try this instead:
<select name="cartags">
<?php
$result = mysql_query("SELECT DISTINCT `Tag` FROM `Products`");
while(list($tag) = mysql_fetch_row($result)) {
echo "<option>".$tag."</option>";
}
?>
</select>
Try this
<select name="cartags">
<?php $result = mysql_query("SELECT Tag, COUNT(Tag) tg Products WHERE ID > '0' GROUP BY Tag HAVING COUNT(Tag)>0 ORDER BY tg DESC");
while($row = mysql_fetch_array($result))
{
echo "<option value=\""; echo $row['tg']; echo "\""; echo ">"; echo $row['tg']; echo " </option>";
}
?>
</select>
It will also display the top tags that have the most first.

How do I create a dynamic set of pull down menus using javascript

I am working on optimizing a form for our website that lets a user complete the it using pull down menus. I have figured out how to populate a single pull down menu based on a PHP query, but I then need another pull down menu to be populated based on that selection. I am attempting to use the onchange attribute for the select tag. I know that my query in the javascript is not dynamic yet, but I am just trying to get it to show the next pull down first, which it isn't. When I select something from the first pull down nothing happens. Thank you advance for any help.
$query2 = "select distinct Provider_Name from CE_ACTIVITY_LIST_T where IS_ACTIVE = 'YES'";
$result2 = mysql_query($query2, $link) or die(mysql_error());
//$row2 = mysql_fetch_array($result2) or die(mysql_error());
echo "<table border='0'><tr><th>";
echo "Course Provider:</th><td><select name='providerName' id='provider'onchange='getResult()'>";
echo "<option SELECTED>Pick Provider</option>";
$i=0;
while($row2 = mysql_fetch_array($result2))
{
echo "<option value=\"" . $row2['Provider_Name'] . "\">" . $row2['Provider_Name'] . "</option>";
$i++;
}
echo "</select></td></tr><tr></tr>";
<script type="text/javascript">
function getResult(field)
{
var field=field;
var isEqualTo=document.getElementById('provider');
document.getElementById('selectCourse').innerHTML = '<?php
include ('connectionOpen.php');
$queryCourse="select Course_Title from CE_ACTIVITY_LIST_T where Provider_Name = 'Test 1' and isActive = 'YES'";
echo "<tr><th>";
echo "Course Title:</th><td><select name='courseTitle'>";
echo "<option SELECTED>Which course?</option>";
$i=0;
while($row2 = mysql_fetch_array($result2))
{
echo "<option value=\"" . $row2['Course_Title'] . "\">" . $row2['Course_Title'] . "</option>";
$i++;
}
echo "</select>";
echo "</td></tr></table>";
?>';
}
</script>
If you want to populate another list then you need to load it with ajax, you can use jQuery to make it easier. First create php script that will generate html for second option list, eg. myscript.php, this script should receive parameter name.
Be sure that jQuery is included. Then modify your javascript as follows:
function onChange()
{
var name = providerName.value;
var url = "path-to-script";
$.get(url, {name:name} function(html){
$("#result").html(html)
});
}
Instead of second option use <div id='result'></div> as placeholder for new option list.

Issue with PHP variable when fetched from MySQL

I have a variable like "Doctor and Surgical" I take this value from Mysql database and store it in a variable. When I echo this variable it gives me only "Doctor"
Can anyone tell me how can I take the above value retrieved from Mysql as an entire variable...
EDIT
Please find the code below
query.php
<form action="process.php" method="post">
<select name="cat">
<?php
$sql="select distinct Category from tbl_1 order by Category asc";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query))
{
echo "<option value=".$row[Category].">".$row[Category]."</option>";
}
?>
</select>
<select name="station">
<?php
$sql_1="select distinct Station from tbl_1 order by Station asc";
$query_1=mysql_query($sql_1);
while($row=mysql_fetch_array($query_1))
{
echo "<option value=".$row[Station].">".$row[Station]."</option>";
}
?>
</select>
<input name="C" type="submit" />
</form>
process.php
$myValue =$_POST['cat'];
$myStation=$_POST['station'];
echo $myValue;
echo "<br/>";
echo $myStation;
$mySqlStm ="SELECT Name FROM tbl_1 WHERE Category='$myValue' and Station='$myStation'";
$result2 = mysql_query($mySqlStm) or die("Error:mysql_error()");
if(mysql_num_rows($result2) == 0){
echo("<br/>no records found");
}
ELSE
{
echo "<table border='1'>";
//ECHO THE RECORDS FETCHED
while($row = mysql_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
}}
Here when I echo $myValue it gives me "Doctor" instead of "Doctor and Surgeon"
I need "Doctor and Surgeon as an entire variable.
You need to quote the value properly:
echo "<option value='".$row[Category]."'>".$row[Category]."</option>";
With your current code, if you look at the source you will probably see something like this:
<option value=Some Category>Some Category</option>
But with proper quotation you'll see the correct value.
You can use this without having to concatenate:
echo "<option value='{$row[Category]}'>{$row[Category]}</option>";
Think of the quotes just like you would a bracket or an html tag. When you open one, you are inside until you close it. In this case, you needs quotes to tell php what to echo out and different quotes that will print for html attributes. It's usually easier to use single quotes for the php echo commands and double quotes for the html code. Then the . just means to stitch a bunch of stuff together without having to put the echo command ten times in a row. So when you have this:
echo '<option value="'.$row[Category].'">'.$row[Category].'</option>';
you can break it down like this (just for your mental clarity, don't actually code this):
echo
'<option value=" '
.
$row[Category]
.
' "> '
.
$row[Category]
.
'</option>'
;
Use single quotes & Just insure the value of $row['Category']
Try it:
echo "".$row['Category']."";

Using PHP to populate a <select></select> dropdown? [duplicate]

This question already has answers here:
Fetching data from MySQL database to HTML dropdown list
(4 answers)
Closed 7 months ago.
<select name="select">
</select>
I want to populate the above tag with values from database.
I have written PHP code up to this.
while($row=mysql_fetch_array($result))
{
}
$row is fetching correct values. How to add it to the <select>
What about something like this :
echo '<select name="select">';
while($row=mysql_fetch_array($result))
{
echo '<option value="' . htmlspecialchars($row['column_for_value']) . '">'
. htmlspecialchars($row['column_for_label'])
. '</option>';
}
echo '</select>';
Of course, up to you to decide which items from $row should be used for the value and the text of each <option>
Just make sure you are escaping the data that comes from your DB -- especially if it can contain HTML ; as you are outputting HTML, this can be done with htmlspecialchars or htmlentities.
Note that those might take a couple of additionnal parameters that I didn't use in my example -- setting those can be useful, depending on the charset you're using.
You can see whats available to use by doing this in the while:
var_dump($result);
exit;
That will print the first result and its array contents. Then you can see what field you want to use to populate the option. From there, you would do something like:
foreach ($result['field'] as $field) {
print '<option value="'.$field.'">$field</option>';
}
Of course this is a very basic example, and as others have noted you may want to clean the data before putting it into a form.
$selected_value="selected_value";
echo '<select name="select">';
while($row=mysql_fetch_array($result))
{
if($selected_value==htmlspecialchars($row['column_for_value']))
$selected=' selected';
else
$selected='';
echo '<option value="'.htmlspecialchars($row['column_for_value']).'"'.$selected.'>'
.htmlspecialchars($row['column_for_label']).
'</option>';
}
echo '</select>';
Some addition to Pascal MARTIN code, for auto selection of some predefined value
I editied the last entry to this and it works perfectly. The only hassle I have now is once the user has submitted the form the dropdown goes blank... Does anyone know a simple solution
echo '<select name="course" id="course" >';
while( $option = mysql_fetch_array($course_results)) {
echo "<option value=".htmlspecialchars($option['cid']).">".htmlspecialchars($option['cname'])."</option>";
}
echo "</select>";
All the above answers will work, but are not proper and require extra work. You should not use echo to output to the screen and you don't have to. The below example assumes you are using objects containing data, but you get the idea.
<select name="sales_person">
<?php foreach ($sales_people as $sales_person){?>
<option value="<?=$sales_person->first_name?> <?=$sales_person->last_name?>"><?=$sales_person->first_name?> <?=$sales_person->last_name?></option>
<?php }?>
</select>
The point being you don't have to echo out the html
echo "<select>";
while( $option = mysql_fetch_array($result)) {
echo "<option>".htmlspecialchars($option['column'])."</option>";
}
echo "</select>";
echo '<select>';
while($row=mysql_fetch_array($result)) {
echo '<option>'.$row['whatever_index'].'</option>';
}
echo '</select>';
Replace 'whatever_index' with the column name you are fetching.

Categories