First time poster and wet-behind-the-ears programmer here, hope you guys can help me out!
I'm trying to create a dropdown list using php/html, and to populate it using a mysqli-call.
Here's what I've got so far:
<?php
require_once 'forbindtilDB.php';
$result = performQuery("SELECT DISTINCT primaer FROM oevelser");
FOLLOWING TWO LINES ARE ONLY TO CHECK RESULT 'MANUALLY' IN UI:
$row = mysqli_fetch_array($result);
echo $row['primaer'];
?>
<html>
<body>
<form>
<select>
<option value="0">Please Select</option>
<?php
while($row = mysql_fetch_assoc($result) )
{
?>
<option value = "<?php echo($row['primaer'])?>" >
<?php echo($row['primaer']) ?>
</option>
<?php
}
?>
</select>
</form>
</body>
</html>
The dropdown is displayed, but it's not getting any contents besides 'Please select' (should be two options at this stage, more to come...)
Any hints on this?
Also, since I'm using DISTINCT to get data from a specific column in the table, should I use something else than 'fetch_assoc' to get my result?
Any input will be appreciated!
Related
I am a complete novice but trying to design my first site in Wordpress. I am trying to retain the value of a dropdown that pulls values from a database after a form is submitted. I have searched many questions and tried many different ways of trying to write selected="selected" in my code but none of them seem to work. Please help.
Here is my code that just pulls from the database but isn't trying to retain the selected value:
<select name = "box1" class="searchbox">
<option value = "">All Values</option>
<?php
global $wpdb;
$ddresult = $wpdb->get_results("SELECT Field1 FROM pc_table ORDER BY Field1 ASC");
foreach($ddresult as $ddrow) {
?>
<option value="<?php echo $ddrow->Field1; ?>"><?php echo $ddrow->Field1; ?> </option>
<?php
} ?>
</select>
How can I add the code to keep the value selected after form submit? Any help much appreciated, thank you.
Try this. It checks if box1 was submitted. Then it compares that value to the items in the options loop. A match will set $selected to the correct attribute, otherwise it will stay an empty string by default. (NB: if form is using get method, then change $POST to $_GET)
<select name = "box1" class="searchbox">
<option value = "">All Values</option>
<?php
global $wpdb;
$ddresult = $wpdb->get_results("SELECT Field1 FROM pc_table ORDER BY Field1 ASC");
foreach($ddresult as $ddrow) {
$selected = '';
if(isset($_POST['box1'])){
if($ddrow->Field1==$_POST['box1']){ $selected = 'selected="selected"'; }
}
?>
<option value="<?php echo $ddrow->Field1; ?>" <?php echo $selected; ?>><?php echo $ddrow->Field1; ?> </option>
<?php
} ?>
</select>
This example of course does not include if you want to save the submitted value to the database and then re introduce it in the output at a later time. If that's what you would like to know, then please leave a comment.
I have the following code:
<td>Province</td>
<td>
<select name="prov">
<?php
$sql1 = mysqli_query($connect, "SELECT * FROM Provincetbl order by Prov_Desc desc");
while ($row1 = $sql1->fetch_assoc()){
?>
<option value="prov1"><?php echo $row1['Prov_Desc']; ?> </option>
<?php
}
?>
</select><br><br></td></tr>
<td>Distrect</td>
<td>
<select name="dist">
<?php
$sql2 = mysqli_query($connect, "SELECT * FROM Distrecttbl order by Distrect_Desc desc");
while ($row2 = $sql2->fetch_assoc()){
?>
<option value="dist1"><?php echo $row2['Distrect_Desc']; ?> </option>
<?php
}
?></select></td></tr>
There are two listboxes prov and dist. I have been trying to figure out how to read the value of either listbox (i.e get it in a variable). I have found a post which states that the value of a listbox is read after the form is posted (in the variable $_Post). However, I am dealing with a listbox which is not sending anything to the server, so why is the value of the listbox read after the form is posted?
Second, I do not have a form element in my page to begin with..?
Other posts have stated that I can read the value of listbox in a variable $prov or $dist. However I cannot seem to echo the contents of these variables to the screen.
Thank you for your help.
I think all the options in the prov listbox will have the same value that you've wrote 'prov1' and the second listbox will have dist1 in all the options
What I recommande you to do is the following :
<option value="$row1['Prov_Desc']"><?php echo $row1['Prov_Desc']; ?> </option>
and for the second one use this :
<option value="$row2['Distrect_Desc']"><?php echo $row2['Distrect_Desc']; ?> </option>
EDIT!!! : LINK = http://i299291.iris.fhict.nl/PHP31/DV3/DV3.php
My problem:
I've made two dropdown boxes with several options. The php code is working and the query gets the right result from the database. But now i want to compare two options.
This is what i've got so far, the problem now is the entire page refreshes when i enter the second value from the other dropdown box.
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form id = "leftDropdown" action= "" method="post">
<select name="objectLinks">
<option value="school">School</option>
<option value="klas">Klas</option>
<option value="geslacht">Geslacht</option>
<option value="lengte">Lengte (CM)</option>
<option value="kg">Gewicht (KG)</option>
<option value="opleiding">Opleiding Ouders</option>
<option value="leeftijdJaar">Leeftijd</option>
<option value="interventie">Deelname interventie?</option>
<option value="pestenVoor">Pestincidenten voor interventie</option>
<option value="pestenNa">Pestincidenten na interventie</option>
<option value="bmi">BMI waarde</option>
<option value="overgewicht">Overgewicht</option>
<option value="allochtonenPerc">Percentage Allochtonen</option>
</select>
<input type="submit" name="sendLinks" value="Go!">
</form>
<form id = "rightDropdown" action= "" method="post">
<select name="objectRechts">
<option value="school">School</option>
<option value="klas">Klas</option>
<option value="geslacht">Geslacht</option>
<option value="lengte">Lengte (CM)</option>
<option value="kg">Gewicht (KG)</option>
<option value="opleiding">Opleiding Ouders</option>
<option value="leeftijdJaar">Leeftijd</option>
<option value="interventie">Deelname interventie?</option>
<option value="pestenVoor">Pestincidenten voor interventie</option>
<option value="pestenNa">Pestincidenten na interventie</option>
<option value="bmi">BMI waarde</option>
<option value="overgewicht">Overgewicht</option>
<option value="allochtonenPerc">Percentage Allochtonen</option>
</select>
<input type="submit" name="sendRechts" value="Vergelijk!">
</form>
<div id = "leftDiv">
<?php
include_once 'dv3ToDB.php'; // connect to database *local or at school's server*
session_start();
if(isset($_POST['sendLinks'])){
$selectedValLinks = $_POST['objectLinks'];
// echo "Jij selecteerde: ".$selectedVal;
echo "<script>console.log('$selectedValLinks');</script>";
// $_SESSION["valLinks"] = $selectedValLinks;
// echo $_SESSION["valLinks"];
$query = "SELECT ($selectedValLinks) FROM pesten ORDER BY ($selectedValLinks) * 1";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Gevonden data in ".$selectedValLinks.": " . $row["$selectedValLinks"] . "<br>" ;
}
}else{
echo "0 results";
}
}
?>
</div>
<div id = "rightDiv">
<?php
if(isset($_POST['sendRechts'])){
$selectedValRechts = $_POST['objectRechts'];
// echo "Jij selecteerde: ".$selectedVal;
echo "<script>console.log('$selectedValRechts');</script>";
// $_SESSION["valRechts"] = $selectedValRechts;
// echo $_SESSION["valRechts"];
$conn = mysqli_connect($host,$username,$password,$database)
or die("verbinding mislukt:".mysqli_connect_error());
$query = "SELECT ($selectedValRechts) FROM pesten ORDER BY ($selectedValRechts) * 1";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Gevonden data in ".$selectedValRechts.": " . $row["$selectedValRechts"] . "<br>" ;
}
}else{
echo "0 results";
}
}
?>
</div>
</body>
</html>
i'm running it local now, let me know if you need me to build a database online to help me out.
How can i code it so the PHP output stays in de left DIV and/or the right DIV?
Thank you so much guys and girls! :)
If you need to use only PHP, without any JavaScript (which could allow you to display the result from the database after selecting each option without reloading the page), I'd suggest that, after submitting one form, you add it's result as a hidden input for the other form, so you could read this variable after submitting the 2nd form.
Like this:
<? // Your code for getting the result of the 1st form above returns a variable $res1
// Now insert this into the 2nd form:?>
<input type="hidden" name="stored2" value="<?echo $res1;?>"/>
This way, you can read the variable $_POST["stored2"] after submitting the 2nd form to get what the 1st form returned before.
Do the same for the 1st form to store the results of the 2nd form if it was filled first.
This way, you can compare the results of submitting 2 forms while using only PHP.
EDIT:
You'll need to place all the database requests before the forms to use this method, and just echo the result in the div later.
You want to make a new <iFrame> and then set that <iFrame>'s id as the target for your form.
e.g.:
<form ... target="newframe">
...
</form>
<iFrame id="newframe"></iFrame>
As Lal mentioned you don't need two forms, just one will work.
You need some code that updates the option to selected, if you don't want it to "stick" on page refresh.
Further reading here;
http://www.w3schools.com/tags/att_option_selected.asp
and here
html select option SELECTED
Even try Jquery;
http://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu
I have the below code. It's a function creating a from containing a dropdown menu and a selectionbox, and is being called from a different page).
<?php
require_once 'forbindtilDB.php';
function populerDropdownsOpretProgram()
{
global $mysqliOOP;
$stmt = $mysqliOOP->prepare("SELECT DISTINCT primaer FROM oevelser ORDER BY primaer ASC");
?>
<form action="temp.php" method="post">
<select multiple>
<option value="0">Vælg ønskede øvelse(r)</option>
<?php
$stmt->execute();
$stmt->bind_result($primaereMuskelgruppe);
while ($stmt->fetch())
{
?>
<option value = "<?php echo $primaereMuskelgruppe;?>" >
<?php echo $primaereMuskelgruppe;
?>
</option>
<?php
}
$stmt->close();
?>
</select>
<?php
$stmt = $mysqliOOP->prepare("SELECT antalreps FROM antalreps ORDER BY antalreps ASC");
?>
<select>
<option value="0">Vælg ønskede antal gentagelser</option>
<?php
$stmt->execute();
$stmt->bind_result($antalreps);
while ($stmt->fetch())
{
?>
<option value = "<?php echo $antalreps;?>" >
<?php echo $antalreps;
?>
</option>
<?php
}
$stmt->close();
?>
</select>
<input type="submit">
</form>
<?php
}
I want to post the user input on a different page (currently temp.php), but I don't know how to handle the fact that the form contents is variables fetched by a mysqli call.
So far I've tried different versions of the below on the temp.php-page
<?php
echo $_POST[$antalreps];
?>
<?php
echo $_POST[$primaereMuskelgruppe];
?>
But I'm getting errors stating that there is undefined variables (antalreps and primaeremuskelgruppe) and undefined indexes...
Also, there's the added complexity that the selection box may return more than one result.
Pretty sure echo $_POST[$antalreps]; etc. is the wrong way to go about this, but I haven't been able to figure out alternatives...
Any hints?
You should add 'name' to your select and then use it.
For example instead of:
<select>
you should have:
<select name="yourname">
and then in php to display its value use:
echo $_POST['yourname'];
and for select multiple you can use:
<select name="othername[]">
and then in PHP use it as array:
foreach ($_POST['othername'] as $item) {
echo $item;
}
of course where I put yourname and othername you should put descriptive name such as colours for color box and similar
Disclaimer: It's been a while since I last wrote any code. The quality of my code is likely to be sub-par. You've been warned.
Greetings.
I am coding a basic form that uses a SELECT list I populate from my database.
However, my user needs the form to be dynamic and wants to be able to select either MasterTable1 or MasterTable2 or MasterTable3...
Instead of hardcoding the table name for the database query that populates the SELECT list, I attempted to implement a basic Ajax action (used example from w3schools)...and that's when I lost my sanity...
I can output <div id='txtHint'></div> in my page and it shows the correct table name that was picked.
But how do I pass the correct table name to my query that will populate my SELECT list???
I tried
<select name="DBFilename" id="DBFilename" size="0">
<option value="">Select Filename</option>
<?php
$sql="select distinct filename from "."<div id='txtHint'></div>";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)){ ?>
<option value="<?php echo $row['filename']; ?>"><?php echo $row['filename']; ?></option>
<?php } ?>
</select>
But to no avail. This is confusing since I can do this...
...
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gettable.php?q="+str,true);
xmlhttp.send();
}
</script></head>
<body><form><select name="SrcTbl" id="SrcTbl" size="0" onchange="showTable(this.value)">
<option value="">Select Data Table</option>
<option value=""> </option>
<option value="MasterTable1">up to 31 days old</option>
<option value="MasterTable2">62 days old</option>
</select>
</form><br /><div id="txtHint"><select name="tabList"><option></option></select> </div>
</body></html>
And the name of my table will be displayed in the SELECT list 'tablist'.
How do I pass the correct table name to my query that will populate my SELECT list? Thanks!!
(Pastebin =>form code)
m8, ajax is mainly used for user experience and populating a select list is so easy mode that it shouldnt be bothered with ajax in the first place!
You should use ajax if you want to use some methods on user submitted data and create an illusion of seamless data exchange between the server and the client, and based on the return results render a corresponding view or an element of the view.
unless you load every element of the view with ajax, you should populate your html with php from the start!
<select name="DBFilename" id="DBFilename" size="whatever since style belongs to css">
<option selected="selected">Select Filename</option>
<?php
$sql="SELECT DISTINCT filename from 'wherever'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)){ ?>
<option value="<?php echo $row['filename']; ?>"><?php echo $row['filename'];?>
</option>
<?php } ?>
</select>
Create a separate php script which returns a list of select options -> values depending on the table name given to it. You must remember to protect against sql injection. Then use ajax to retrieve the list and insert it into the select.