PHP echo out data into HTML drop drop down menu - php

I have a HTML etc.. tags now what I want to achieve is upon a selection of ie. i want to load the related info from database to in a new tag with as many tags.
I am using PHP to do achieve this now at this point if for example i choose option1 then the query behind it retrieves relevant information and stores it in a array, and if I select option2 exactly the same is done.
The next step I made is to create a loop to display the results from array() but I am struggling to come up with the right solution to echo retrieved data into etc. As its not my strongest side.
Hope you understand what I am trying to achieve the below code will clear thing out.
HTML:
<select id="workshop" name="workshop" onchange="return test();">
<option value="">Please select a Workshop</option>
<option value="Forex">Forex</option>
<option value="BinaryOptions">Binary Options</option>
</select>
PHP:
$form = Array();
if(isset($_POST['workshop'])){
$form['workshop'] = $_POST['workshop'];
$form['forex'] = $_POST['Forex'];
$form['binary'] = $_POST['Binary'];
//Retrieve Binary Workshops
if($form['workshop'] == 'Forex'){
$sql2 = "SELECT id, course, location FROM courses WHERE course LIKE '%Forex%' OR course LIKE '&forex%'";
$query2 = mysqli_query($link, $sql2);
while($result2 = mysqli_fetch_assoc($query2)){
//The problem I am having is here :/
echo "<select id='Forex' name='Forex' style='display: none'>";
echo "<option value='oko'>.$result[1].</option>";
echo "</select>";
print_r($result2);echo '</br>';
}
}else{
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%Binary%' OR course LIKE '%binary%'";
$query = mysqli_query($link, $sql);
while($result = mysqli_fetch_assoc($query)){
print_r($result);echo '</br>';
}
}
}

Try this code:
$query2 = mysqli_query($link, $sql2);
echo "<select id='Forex' name='Forex' style='display: none'>";
while($result2 = mysqli_fetch_assoc($query2)){
echo "<option value='oko'>{$result['course']}</option>";
}
echo "</select>";
echo '</br>';

From the top in your php:
// not seeing uses of the $form I removed it from my answer
if(isset($_POST['workshop'])){
$workshop = $_POST['workshop'];
$lowerWorkshop = strtolower($workshop);
// neither of $_POST['Forex'] nor $_POST['Binary'] are defined in your POST. you could as well remove those lines?
//Retrieve Binary Workshops HERE we can define the sql in a single line:
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%$workshop%' OR course LIKE '&$lowerWorkhop%'";
$query = mysqli_query($link, $sql); // here no need to have two results
// Here lets build our select first, we'll echo it later.
$select = '<select id="$workshop" name="$workshop" style="display: none">';
while($result = mysqli_fetch_assoc($query)){
$select.= '<option value="' . $result['id'] . '">' . $result['course'] . '</option>';
// here I replaced the outer containing quotes around the html by single quotes.
// since you use _fetch_assoc the resulting array will have stroing keys.
// to retrieve them, you have to use quotes around the key, hence the change
}
$select.= '</select>';
}
echo $vSelect;
this will output a select containing one option for each row returned by either of the queries. by the way this particular exemple won't echo anything on screen (since your select display's set to none). but see the source code to retrieve the exemple.

Related

PHP - populate a select drop down from MySQL DB and have that field auto-populated in a form

I am trying to accomplish two things with the code below. Firstly I want my select options to be populated form my database. Secondly I want the field in the form to have the stored value selected on page load (like in a profile for a member). The way I have implemented below works, kind of, but I have two problems. Firstly if you open the dropdown then the selected option appears twice (once at the top and once in its normal position). Secondly if it is a required field then the user has to open the dropdown and select it again, even though it is appearing in the field (horrible ux). If it is not a required field the form acts as if nothing is selected and I get a Undefined index error further down the line. I am very sure there is a better way to implement what I am trying to achieve that wont give me these problems... all help greatly appriciated.
<?php
$query6 = "SELECT catname FROM travisor_catagory";
$result6 = mysqli_query($conn, $query6) or die(mysqli_error($conn));
$queryread3 = "SELECT * FROM travisor_catagory WHERE id = $catagory";
$result3 = mysqli_query($conn, $queryread3) or die(mysqli_error($conn));
if (mysqli_num_rows($result3) > 0) {
while ($row = mysqli_fetch_assoc($result3)) {
$cat = $row["catname"];
}
}
echo "<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<option disabled selected value> $cat </option>";
if (mysqli_num_rows($result6) > 0) {
while ($row2 = mysqli_fetch_assoc($result6)) {
$catagory2 = $row2["catname"];
echo "<option>$catagory2</option>";
}
}
echo "</select>"
?>
Don't mix things up so much.....
When you get into larger programs, you will get lost really quickly, so K.I.S.S.!!!
You can 'jump' in/out of HTML and back to PHP to echo the $options variable, then back to HTML to complete the select. (this is my description of it when I teach newbies - this concept of 'jump in/out' works for PHP, HTML, JS - well any languages that you can combine in one page... - it is worth grasping the concept!)
First, get the options you will need with ONE query (watch how we take care of the selected one as well) - this will make a 'packet' of data in the $options variable.
<?php
// declare some values that we'll use later
$options = '';
// gather the data for the options
$sql = "SELECT id, catname FROM travisor_catagory";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$selected = '';
if($category == $row['id']){
$selected = "selected";
}
$options .= '<option ' . $selected . ' value="' . $row["id"] . '">" . $row["catname"] . "</option>";
}
}
// now we will 'jump' out of PHP and back to HTML
?>
<!-- we are in HTML, so comments and language changed... -->
<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<!-- here we 'jump' out of HTML and into PHP to use the $options variable -->
<?php echo $options; // and back out of PHP to HTML... ?>
<!-- where we finish up our select and whatever other HTML things -->
</select>
</div>
That should take care of both your issues with what you had.....
BTW, it looks like you are using Bootstrap - if so, I HIGHLY recommend you check this out (changed my life about fighting with select boxes! :) Bootstrap Select

How can I add option values in the select tag with PHP

I'm working with PHP and MySQL and I want to retrieve some data from db into a select html tag.
What I did was:
<select class='form-control select2' name='product_cat' style='width: 100%;'>
".get_cats()."
</select>
And the function get_cats goes like this:
function get_cats(){
$get_cats = "select * from categories";
$run_cats = mysqli_query($GLOBALS['con'],$get_cats);
$return = '';
while($row_cats = mysqli_fetch_array($run_cats)){
$cat_id = $row_cats['cat_id'];
$table_id = $row_cats['table_id'];
$cat_title = $row_cats['cat_title'];
$totalNumberOfProductsQuery = "SELECT * FROM products WHERE product_cat = '" . $cat_id. "'";
$catsProducts = mysqli_query($GLOBALS['con'], $totalNumberOfProductsQuery);
if (!$catsProducts) {
die(mysqli_error($GLOBALS['con']));
}
$totalProductsForCats = mysqli_num_rows($catsProducts);
echo "
<option value='$cat_id'>$cat_title</option>
";
}
}
It simply grabs the data from database correctly but the problem is, it prints them out this way:
capture
While the Product Category field is empty and the options of select tag is going up the form field.
I guess this issue is because of the while() statement which I used at the function.
What is the alternative way of doing this function with another command? How can I place the option list correctly inside this function?
Thanks.
The problem is most likely the way you are outputting the content. When you put...
<select class='form-control select2' name='product_cat' style='width: 100%;'>
".get_cats()."
</select>
What you are expecting to happen is that you will take the return value of get_cats() and insert it into the HTML. BUT in the get_cats() function, you aren't returning the value - you're echoing the values as you go along What can happen is that this then gets mixed in rather than joined as you expect it to be (as you can see from your output). Instead you should build up a string and return the full HTML back to the calling code so that can echo it out...
function get_cats(){
$get_cats = "select * from categories";
$run_cats = mysqli_query($GLOBALS['con'],$get_cats);
$return = '';
while($row_cats = mysqli_fetch_array($run_cats)){
$cat_id = $row_cats['cat_id'];
$table_id = $row_cats['table_id'];
$cat_title = $row_cats['cat_title'];
$totalNumberOfProductsQuery = "SELECT * FROM products WHERE product_cat = '" . $cat_id. "'";
$catsProducts = mysqli_query($GLOBALS['con'], $totalNumberOfProductsQuery);
if (!$catsProducts) {
die(mysqli_error($GLOBALS['con']));
}
$totalProductsForCats = mysqli_num_rows($catsProducts);
// Build up HTML
$return .= "
<option value='$cat_id'>$cat_title</option>
";
}
return $return;
}
A couple of other things.
Rather than using $GLOBALS['con'], pass in the connection to the
function, this is a preferred method of doing it.
Look into prepared statements and bind variables.
You could reduce the SQL to 1 statement, this means that just 1 SQL
is used.
Simple answer: Write the generated code into a string and return it at the end of the function. Further echo your function. Then it will work.

Get value form same table

I have dropdown menu with 3 values.
and here is my table (table name is Sms)
What I want to do? Example : If I choose 2,49 and press submit, then I get sonum value.
This is my form
<div class="col_12" style="margin-top:100px;">
<div class="col_6">
<label for="asukoht">Vali Hind</label>
<form class="vertical" method="GET">
<select name="hind">
<option value="1">-- Vali --</option>
<?php
// Tegin dropdown menüü, kust saab valida komponendi, mille alla see pilt läheb
$andmed = mysql_query("SELECT * FROM Sms");
// Dropdown menüü
while($rida = mysql_fetch_array($andmed)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
?>
<input type="submit" name="add" id="add">
</form>
I tried something like this
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
I think it should be pretty easy, but I'm looking for a solution and I didnt found it.
Thank you for helping !
You need to work on SQL and Loop.
Based on your code:
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
First we do change the query including $_GET parameter.
So this:
$sql = "SELECT sonum FROM `Sms`";
Will become:
$sql = "SELECT sonum FROM `Sms` WHERE id = ".$_GET['hind'];
It will be better if you check that the var exist and is setted with something like:
if(isset($_GET['hind']) && is_numeric(trim($_GET['hind']){//Code here}
But it is off-topic.
Now let's change echo $sql; with a loop, we need to loop and fetch the data.
while($result = mysql_fetch_array($sql)){
echo '<option value="'.$result ['id'] . '">'.utf8_encode($result ['hind'] ). '</option>';
}
I've only changed what i know, you know your system ^_^
You should do:
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
Then do :
echo mysql_query($sql);
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
while($rida = mysql_fetch_array($sql)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
Do not use MYSQL queries...try MySQLi or PDO with prepared statement.

Adding a variable value as an option in a PHP echo created drop down menu

I am using a PHP script within an HTML page to create a dropdown menu with results populated from a database. I am using the PHP script in the HTML page because I'd like the dropdown menu to remain on the same page as a number of options.
When creating an option in the dropdown menu via an echo, it won't allow me to use the value of a variable (i.e. the value of a field in the database that has been retrieved) in the option tag. Here is the code:
<select name="comics">
<OPTION>Select an option</OPTION>;
<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<option> .$row['comicName']. </option>";
}
?>
</select>
As is, the code creates the drop down menu and adds the "Select an option" line. The second option is created, but the value reads as " .$row['comicName']. " instead of, for example, "Superman".
Thanks in advance.
Have you named the file with a php extension ? try doing a print_r with $result before the while loop
Your solution tries performing concatenation without closing the double-quotes first, so it treats the variable as a string. Try this:
echo "<option>" . $row['comicName'] . "</option>";
Try:
<select name="comics">
<OPTION>Select an option</OPTION>;
<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<option value='".$row['comicName']."'>".$row['comicName']."</option>";
}
?>
</select>
Let me know if works.

Using a mysql data base to populate a second drop down box automatically based off of first drop down box

I need to have a selection box display options that are based off of the selection from the drop down box right above it. Once the user selects the Car Make, then I want the Car Models of the car make to be options to be selected.
I have been able to get the car makes options to be displayed from my mysql data base, but now I need the car models of only that make. My data base has two collumns, one for the Make and one for the Model.
The top section of PHP is the way i get the make, and the bottom is my attempt to get the model, but it displays hundreds of models, instead of just the few I want. I heard that AJAX or javascript can automatically upload the results, which would be nice. Any help is great. thanks!
</div>
<?php
mysql_connect('localhost', '*****', '******');
mysql_select_db('*************');
$sql = "SELECT Make FROM CarMakes";
$result = mysql_query($sql);
echo "<select name='carmake3'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Make'] . "'>" . $row['Make'] . "</option>";
}
echo "</select>";
?>
<?php
mysql_connect('localhost', '******', '**********');
mysql_select_db('*************');
$sql = "SELECT Model FROM myTable";
$result = mysql_query($sql);
echo "<select class='modelbox' name='carmodel3'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Model'] . "'>" . $row['Model'] . "</option>";
}
echo "</select>";
?>
<input type="text" maxlength="4" name="car3year" placeholder="year" class="WriteInBox"/>
<input type="text" maxlength="6" name="car3miles" placeholder="miles" class="WriteInBox"/>
</div>
$sql = "SELECT Model FROM myTable";
This clearly is giving you the results you are asking for. It will select all models.
Your sql should look like
$sql = "SELECT Model FROM myTable WHERE Make='Make'";
The where limits you to retrieve only models associated with the specific Make you have selected.
To do it with AJAX, are you using jQuery? Straight JavaScript with an Ajax call? Please provide more information for answering that part of your question.
This probably isn't the best way to do this, but when I have had to do things like this before, I usually use the php to populate some javascript variables in my header and then use javascript to create the selects. Also, I'm assuming that there is something in your database that maps certain models to certain makes of vehicles.
<script>
var makes = new Array();
var models = new Array();
<?php
$sql = "SELECT Make FROM CarMakes";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
?>
makes[] = <?php echo json_encode($row['Make']); ?>;
<?php
}
$sql = "SELECT Make FROM CarMakes";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
?>
models[] = <?php echo json_encode($row['Model']); ?>;
<?php
}
?>
</script>
From here, you can create the selects and populate the options of the first one with the elements of the makes array. Then add an onChange event to the first select to populate the second select.
EDIT For select creation:
<select id="make-select" onChange="updateModels()">
</select>
<select id="model-select">
</select>
<script>
$(function() {
$.each(makes, function (index, value) {
$(#make-select).append($('<option>') {
value: value,
text: value
});
});
}
</script>
Then just create a function that called updateModels that will update model-select based on the selected value of make-select. Again, you'll need somehting that associates models with makes in your database, and then you might have to make the makes variable an object instead of just an array.
var models = new Object()
<?php
$sql = "SELECT Model-Make, Model FROM CarMakes";
...
models.make = <?php echo json_encode($row['Model-Make']); ?>;
models.model = <?php echo json_encode($row['Model']); ?>;
...
?>

Categories