I am trying to fetch all "requestors" from a table and offer them as options in a form. As far as I know I didn't fetch the first row before but somehow my code misses the first entry.
Also when I submit the form and try to get the selected value with $_POST it doesn't take the selected value but instead takes the entry before that one.
Here is the code:
<select name="requestor">
<option value="%">Please select Requestor</option>
<?php
$con=mysqli_connect("localhost","username","password","database");
//============== check connection
if(mysqli_errno($con))
{
echo "Can't Connect to mySQL:".mysqli_connect_error();
}
$logins = mysqli_query($con, "select Login_name from login");
while ($dsatz = mysqli_fetch_assoc($logins))
{
echo $dsatz["Login_name"] . "<option value=". $dsatz["Login_name"]."</option>" . "<br />";
}
mysqli_close($con);
?>
</select>
try
echo "<option value='".$dsatz["Login_name"]."'>".$dsatz["Login_name"].'"</option>";
within the loop
Related
I have a database that I want to get data out onto a website. It contains states listed by name and id. Counties listed by id, namne , and state that contains thems ID and then clubs that exist , with a reference to the county id's that they exist in and columns for their actual data.
What I've got :
A drop down menu that populates itself with state id and name.
What I'd like to accomplish:
On selection of state , let's say ny , take it's id and use this in gathering another mysql array for the county drop down. I'd like it to dynamically occur on selection of state , maybe even giving a count of results next to the drop down.
$resstate = mysql_query("SELECT * FROM state ORDER by longstate;") or die("Note: " . mysql_error());
State:
<select name="State" size=1>
<?
while( $rs = mysql_fetch_array( $resstate ) ) {
echo "<option value=" .$rs['id'] . ">" . $rs['longstate'] . "</option>";
}
echo "</select>";
?>
I know I could use a JavaScript onChange="this.form.submit()" on the first drop down, but it's my understanding that I'd then be making a new page at that point and don't know if I could keep the functionality of the state drop down, say if you accidentally chose new Hampshire when you wanted New York.
here's an example of the current array filling the drop down :
http://snowmobileamerica.com/countytest.php
----EDIT---
Using Dagons Advice , I looked into Ajax.
I made a php file that's supposed to query the database based on a reference to getcounty.php?q=
The file is created as follows :
<?php
$q=$_GET["q"];
$cn=mysql_connect("localhost","user","password") or die("Note: " . mysql_error());
mysql_select_db("snowusa_clubs", $cn);
$sql="SELECT * FROM county WHERE state_id = '".$q."' ORDER by name";
$result = mysql_query($sql);
echo "<select name="County" size=1>";
while($rc = mysql_fetch_array($result))
{
echo "<option value=" .$rc['id'] . ">" . $rc['name'] . "</option>";
}
echo "</select>";
mysql_close($cn);
?>
If i try to run it manually http://www.snowmobileamerica.com/getcounty.php?q=33 I get a 500 internal server error...
Any ideas where I went wrong?
try adding an id to the element, then make an ajax call to a handler with jquery:
$("#State").change(function() {
$.post("path/to/request handler/" , { "State" : $(this).val() },
function(data){
if (data == "OK"){
//add some elements here
} else {
//handle an error here
}
});
});
not able to comment yet.
but for the second question try:
<?php
$q=$_GET["q"];
$cn=mysql_connect("localhost","user","password") or die("Note: " . mysql_error());
echo "Conn ok<br>";
mysql_select_db("snowusa_clubs", $cn);
echo " Database opened<br>";
$sql="SELECT * FROM county WHERE state_id = '$q' ORDER by name";
$result = mysql_query($sql);
echo " Database queried <br>";
echo "<select name='County' size=1>";
while($rc = mysql_fetch_array($result))
{
echo "<option value='" .$rc['id'] . "'>" . $rc['name'] . "</option>";//added single quotes in the value
}
echo "</select> ";
mysql_close($cn);
?>
I have a PHP dropdown of a list of groupnames (together with id, so it can be updated). In this FORM page you can change the groupname specified for an item by choosing possibilities from the dropdown coming out from the database. My code below works, but there must be a better way, because I get the first field as the currently set, and then all the possibilities, so I get this record twice.
Example:
- Keyboard (Currently set)
- Speakers (Possible to choose, straight from DBS)
- Midi Controllers (Possible to choose, straight from DBS)
- Keyboard (Possible to choose, straight from DBS)
- Drum set (Possible to choose, straight from DBS)
As you see I get the currently set record again.
My code:
echo "<select name='itemgroupid'>";
// CHOOSE CURRENT SET RECORD AS SELECTED ITEM
echo "<option value='" . $itemgroupid . "'>";
$selected="
SELECT item.itemid, itemgroup.itemgroupname, itemgroup.itemgroupid
FROM item, itemgroup
WHERE item.itemid=$itemid";
$selectedresult=mysql_query($query) or die("query fout " . mysql_error() );
while($record=mysql_fetch_array($selectedresult) ) {
echo "" . $itemgroupname . "</option>";
}
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
There are 2 ways to achieve what you're looking for:
1) To show the selected item at the top of the dropdown
echo "<select name='itemgroupid'>";
// CHOOSE CURRENT SET RECORD AS SELECTED ITEM
echo "<option value='" . $itemgroupid . "'>";
$selected="
SELECT item.itemid, itemgroup.itemgroupname, itemgroup.itemgroupid
FROM item, itemgroup
WHERE item.itemid=$itemid";
$selectedresult=mysql_query($query) or die("query fout " . mysql_error() );
while($record=mysql_fetch_array($selectedresult) ) {
echo "" . $itemgroupname . "</option>";
}
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup WHERE item.itemid != $itemid";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
2) Show the selected item in it natural place
echo "<select name='itemgroupid'>";
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]";
if( $itemid == $nt['itemgroupid'] ) echo ' selected="selected"';
echo ">$nt[itemgroupname]</option>";
}
echo "</select>";
HTH
OK
In your code.
rather than output your selected value at the top, do it the proper way :)
Select your current item (make a note of the itemgroupid for example)
then in your output
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option ";
if ($savedid==$nt[itemgroupid]) echo "selected ";
echo "$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
This will produce with $savedid=1
<option value=0>group 0</option>
<option selected value=1>group 1</option>
<option value=2>group 2</option>
Add the default selected record to a empty array first like
toDisplay = array('selected_record');
Then, get the data from the database using your sql and append it to this array.
Later run a array_unique on it and finally using a loop create the html output string, in the same way you are doing it now.
Ok so here is my code:
$select_status = 0;
$select_status = "<select name='status'>\n";
$select_status .= "<option value=''>SELECT ONE</option>\n";
$sdataset = mysql_query("SELECT id, name FROM phponly_category") or die(mysql_error());
while($srow=mysql_fetch_assoc($sdataset)) {
echo implode(", ", $srow);
echo "<br />";
$select_status .= "<option value='".$srow['name']."'";
$select_status .= ">".$srow['name']."</option>\n";
} // end while loop
echo "out of the loop";
$select_status .= "</select>\n";
// now insert the <select> list control into the page
echo $select_status;
The code works fine until the last row when it breaks. I cannot get the echo $select_status printed.
I have tried to see what is going on with the SQL query results by printing each row but everything looks fine there. For some reason, at the last row the while loop breaks and even the code after while loop doesn't get executed.
Don't do the or die(mysql_error()) portion in the while test...do it before.
if($sdataset==false) {
die(mysql_error());
}
while($srow=mysql_fetch_array($sdataset)) {
$select_status .= "<option value='".$srow['name']."'".">".$srow['name']."</option>\n";
} // end while loop
The or die() on your while() loop will actually kill the script when you read the end of the result set. mysql_fetch will return false, triggering the or die().
While checking for errors is good on queries, you can't do it like this on the fetching part, because you get false positives like this.
I personally don't like to echo out html code, if your goal is to do validate whether there's result comes out of the query, you can do something like this
<?php
$sdataset = mysql_query("SELECT id, name FROM phponly_category");
if (mysql_num_rows($sdataset) > 0) {
?>
<select name='status'>
<option value=''>SELECT ONE</option>
<?php
while($srow = mysql_fetch_array($sdataset)) {
?>
<option value='<?php echo $srow['name'] ?>'><?php echo $srow['name'] ?></option>
<?php } // end while loop ?>
</select>
<?php
} // end of if
else {
// Whatever you wanna put here
}
?>
EDITED: There's a typo at mysql_num_rows, try this one again
Use mysql_fetch_assoc so you can get the data using the field name as the key.
<?php
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('test');
$select_status = "<select name='status'>\n";
$select_status .= "<option value=''>SELECT ONE</option>\n";
$sdataset = mysql_query("SELECT id, name FROM phponly_category") or die(mysql_error());
while($srow=mysql_fetch_assoc($sdataset)) {
$select_status .= "<option value='".$srow['name']."'".">".$srow['name']."</option>\n";
} // end while loop
$select_status .= "</select>\n";
echo $select_status;
?>
Note: The use of this extension is discouraged. Take a look at mysqli or PDO.
I have a web site that contains an HTML form, in this form I have a dropdownlist with list of agents that works in the company, I want to fetch data from MySQL database to this dropdownlist so when you add a new agent his name will appear as an option in the drop down list.
<select name="agent" id="agent">
</select>
To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.
// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query
echo '<select name="DROP DOWN NAME">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.htmlspecialchars($row['something']).'">'.htmlspecialchars($row['something']).'</option>';
}
echo '</select>';// Close your drop down box
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
You need to fetch all rows from the database and then iterate over them, displaying a new <option> for each one of them. Pay attention to avoid XSS by using htmlspecialchars().
$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
// Select all values from the table Agents
$stmt = $pdo->prepare("SELECT Id, Name FROM Agents");
$stmt->execute();
echo '<select name="agent" id="agent">';
// For each row from the DB display a new <option>
foreach ($stmt as $row) {
// value attribute is optional if the value and the text is the same
echo '<option value="'.htmlspecialchars($row['Id']).'">';
echo htmlspecialchars($row['Name']); // The text to be displayed to the user
echo '</option>';
}
echo '</select>';
If you want to preselect one of the values, then you need to apply selected attribute to one of the <options>:
$selected = 'Somebody';
echo '<select name="agent" id="agent">';
foreach ($stmt as $row) {
if ($selected === $row['Name']) {
echo '<option value="'.htmlspecialchars($row['Id']).'" selected >';
} else {
echo '<option value="'.htmlspecialchars($row['Id']).'">';
}
echo htmlspecialchars($row['Name']);
echo '</option>';
}
echo '</select>';
What you are asking is pretty straight forward
execute query against your db to get resultset or use API to get the resultset
loop through the resultset or simply the result using php
In each iteration simply format the output as an element
the following refernce should help
HTML option tag
Getting Datafrom MySQL database
hope this helps :)
I have a dropdown box which is populated through MySQL:
echo "<form>";<br>
echo "Please Select Your Event<br />";
echo "<select>";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo "<option>";
echo $row['eventname'];
echo "</option>";
}
echo "</select>";
echo "<input type='submit' value='Go'>";
echo "</form>";
How do i make it that if one clicks submit it will display a value from a MySQL db
Thanks for the help
Just change your query like SELECT result FROM somedb WHERE eventname = '".$eventname."'
Then you just do: (remember to check before while has user already requested info)
The value was: <?php print $row["result"]; ?>
Remember to check $_POST["eventname"] with htmlspecialchars before inserting it to query.
1) Give a name to your <select>, i.e. <select name='event'>.
2) Redirect your form to the display page (and set method POST): <form method='POST' action='display.php'>
3) just display the selected value: <?php echo $_POST['event']; ?>
If you want to use the same page, give a name to your submit button and then do this:
<?php
if (isset($_POST['submit']))
echo $_POST['event'];
?>
Hope it helps.