I am trying to make a dropdown list with values from a database, but when I try testing whether the value was taken in, I get nothing.
<select name = "student_id">
<option value="" >choose student</option>
<?php
require_once('../mysqli_connect.php');
$getnames = #mysqli_query($dbc, "SELECT student_id, first_name, last_name FROM students");
while ($row = mysqli_fetch_array($getnames))
{
?><option value = "<?php echo $row['student_id']; ?>">
<?php echo $row['student_id'] . ' ' .$row['first_name'] . ' '. $row['last_name'];
?></option>"; <?php
}
?>
</option>
</select>
The list appears to be fine, showing the student id, first name and the last name of all entries in the database, but when I test the value taken in with this
$studentid = trim($_POST['student_id']);
echo $studentid;
require_once ('../mysqli_connect.php');
?>
And it does not return anything. Everything seems to work with other lists where I did not use any loops and just typed out each option, but I can't find issues In the loop.
Sorry for the terrible question.
?><option value = "<?php $row['student_id']; ?>">
^---missing echo
If you'd done any basic debugging, like a view source of your generated html, you'd have seen that all of your option values are empty...
So, not, it's not the option refusing to store a value. it's doing EXACTLY what YOU told it to: send an empty/blank value to the server.
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.
Okay, I'm reframing this whole question because the earlier version was a bit convoluted.
Here's the scenario:
I have a MySQL table called "churches."
I have a form with four selects. The options are drawn dynamically from the table, so that users can search on four table columns to find churches that fit the criteria (country, state/province, city, presbytery)
I also have working code to get all the table data to display.
What I haven't figured out is how to use the selected option from the form to filter the results.
My current code is below:
<form action="display0506b.php" method="post">
<select name="country">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT country FROM churches");
$query_display = mysqli_query($link,"SELECT * FROM churches");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['country'] . "</option>";
}
?>
</select>
<select name="state">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT state FROM churches WHERE state != ''");
$query_display = mysqli_query($link,"SELECT * FROM churches WHERE state != ''");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['state'] . "</option>";
}
?>
</select>
<input type="submit" value="Go!">
</form>
<?php
if(isset($_POST['country']))
{
$name = $_POST['country'];
$fetch = "SELECT * FROM churches WHERE id = '".$name."'";
$result = mysqli_query($link,$fetch);
echo '<div class="churchdisplay">
<h4>' .$row['churchname'].'</h4>
<p class="detail">' .$row['detail'].'</p>
<p><b>' .$row['city'].'</b>, ' .$row['state'].' ' .$row['country'].'</p>
<p>' .$row['phone'].'</p>
// etc etc
</div>';
}
else{
echo "<p>Please enter a search query</p>";
}
?>
Note that in the form above, I only have two selects for illustration, but ultimately I will have four, as mentioned; and I am only attempting the country selection at this point to keep things simple. Ultimately, I will need the ability to select any (and preferably all) of the four categories.
As you can see, this code does attempt to "grab" the selected value from the form, but it's not working. I've pondered numerous tutorials and examples, but none of them do exactly what I'm after, and as an extreme PHP novice, I'm stumped.
So the question: how do I tweak this so that I can "grab" the form selection and display the relevant results from my table?
Edit: I am using mysqli syntax, and want to just use PHP and MYSQL (no Ajax etc) if possible.
Well, it looks like I've finally found what I needed here:
display result from dropdown menu only when value from it is selected
Or, I should say, I've got it to work with one select option. Still need to see if I can figure out how to get four working together.
I have a music database with a PHP front end where you can add/edit/delete artists, albums, tracks using the web client. The last real problem I have is getting a select box to automatically select an option I pass to the page.
Example:
On a page called 'createCD.php' I have this code:
echo "<td><a href=\"editCD.php?cdTitle=".rawurlencode($row['cdTitle'])."&cdID=$row[cdID]&artID=$row[artID]&cdGenre=".rawurlencode($row['cdGenre'])."&cdPrice=$row[cdPrice]\" </a>Edit</td>";`
This is used as a link to the next page, and collects all the information about an album in the database and sends in to a page called 'editCD.php'.
Now on this page, all the information is used to fill out the webpage as shown here (there is more but for the purposes of this post, only the first select box matters):
Artist Name:
<!-- dropdown with artist name -->
<?php
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'">'.$row['artName'].'</option>';
}
echo '</select>';
?>
<p>
Album Title:
<input id="cdTitle" type="text" name="cdTitle" value ="<?php echo htmlspecialchars($cdTitle); ?>" />
</p>
What I would like is for the "selected" option for 'artID' to be the value that is passed to the page. Using the associative array, I was able to display the 'artName' associated with the 'artID'. Currently, all the information about the album appears correctly apart from the 'artName' and it defaults to the first value. This is a problem as if a user simply clicks "Update" it will update the name to the default name, therefore changing the database entry by accident.
I know I need to be using
<option selected ...>
but I'm not sure on the syntax to use.
<?php
$artID = $_GET['artID']; // get the artID from the URL, you should do data validation
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'"';
if ($artID == $row['artID']) echo ' selected'; // pre-select if $artID is the current artID
echo '>'.$row['artName'].'</option>';
}
echo '</select>';
?>
$artId = $_GET['artID'];
while ($row = mysqli_fetch_assoc($result)) {
$selected = $artId == $row['artID'] ? 'selected' : '';
echo '<option value="'.$row['artID'].'" '.$selected.'>'.$row['artName'].'</option>';
}
First you get the id via $_GET['artID']. (In a real scenario use intval or something to prevent sql injection)
Then check in the loop if the id from database is the same as the id from GET and when it is print "selected, else nothing.
I want to create a php page that contains a html drop down list of people's names (as the option
text) and then their age (as the value). Below is my form for you to see (almost what I mean) which I hard coded:
<form>
<select name="nameOption">
<option value="">Select your name:</option>
<option value="45">Mary Smith</option>
<option value="16">Lily Roe</option>
<option value="32">Elliot Perkins</option>
</select>
<p><input type="submit" name="submit" value="Submit"/>
<input type="reset" value="Reset" />
</form>
What I want to do (or been trying to do) is to create the drop down list by running a SQL query to obtain the data (the people's name and age) from my database (unlike what I written above) and then when I click on one of the options, only their value or age should appear. So basically, I need to implement the data from the database into a drop down list
Now it's here where I am stuck. I am familiar with writing SQL statements for tables but I seem to get puzzled when I try to create a SQL statement for a drop down list in a php tag.
How would I write it? Like:
$sql = "SELECT name, age FROM person WHERE name = ". $person. ";
or
$nameOption = $_POST['nameOption'];
print_r ($nameOption);
with selecting a database:
$conn = mysql_connect("localhost", " ", " ");
mysql_select_db(" ", $conn)
I know it may seem like a dull answer but I need help. How would I implement SQL query to a drop down list? I would love your help.
As you have to enclose string in quotes, change your query to
$sql = "SELECT name, age FROM person WHERE name = '$person'";
and for showing dropdown dynamically you can do like
$query=mysql_query($sql);
echo '<select name="nameOption">
<option value="">Select your name:</option>';
while($result=mysql_fetch_array($query))
{
echo '<option value="'.$result['age'].'">'.$result['name'].'</option>';
}
echo '</select>';
You should do like that
<select name="nameOption">
<?php
$query = mysql_query($sql);
while( $row = mysql_fetch_array($query) ) {
echo '<option value="'.$row['age'].'">"'.$row['name'].'"</option>';
}
?>
</select>
You need to get the full list of people from the database first, then iterate through that outputting each option tag for each row:
$cnx = new Mysqli('localhost', 'username', 'password', 'database_name');
$people = $cnx->query("SELECT name, age FROM person");
echo '<select name="nameOption">';
while($person = $people->fetch_assoc())
{
echo '<option value="' . $person['age'] . '">' . $person['name'] . '</option>';
}
echo '</select>';