Dropdown Menu to Query Database - php

First of I apologize if this is a dumb question - I'm just starting to pick up my php/mysql skills. I'm making a dropdown form with 3 dropdowns. I want to be able to trigger a query from the form. You select Part Type, Make, Model hit submit and a table of results is displayed.
I have my form populated with 3 arrays and when you hit submit, I can echo the key of each selected item to the page:
echo '<form action="dbBrowse.php" method="post">';
$mak = array (0 => 'Make', 'Ford', 'Freightliner', 'Peterbilt', 'Sterling', 'Mack', 'International', 'Kenworth', 'Volvo');
$mod = array (0 => 'Model', 'Argosy', 'Midliner');
$p = array (0 => 'Part', 'Radiator', 'Charge Air Cooler', 'AC');
echo '<select name="drop1">';
foreach ($p as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '</select>';
echo '<select name="drop2">';
foreach ($mak as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '<select name="drop3">';
foreach ($mod as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '</form>';
//echo keys of selection
echo $_POST['drop1'];
echo "<br />";
echo $_POST['drop2'];
echo "<br />";
echo $_POST['drop3'];
//these echo something like 1, 1, 3 etc. to my page
Where I'm getting lost is I'm looking to take the selected options and insert them into a query something like this:
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" . AND WHERE make = "$makeTypeVar" . AND WHERE model = "$modelTypeVar"');
$partTypeVar being the corresponding value to the key that is being returned from the array.
I'm driving myself crazy trying to figure out how to make that happen. Eventually I want to expand this further but just being able to create a mysql statement with the values selected would make my day right now. I understand the concept of what needs to happen but I'm unsure of how to accomplish it. Any help or pushes in the right direction would be greatly appreciated.

First of all, you have to delete the . char in your SQL query, there's no need to use it for now and of course assign the correct values to the variables.
$partTypeVar = mysql_real_escape_string($_POST['$drop1']);
$makeTypeVar = mysql_real_escape_string($_POST['$drop2']);
$modelTypeVar = mysql_real_escape_string($_POST['$drop3']);
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" AND WHERE make = "$makeTypeVar" AND WHERE model = "$modelTypeVar"');
I am assuming that's the correct order of your variables.
I hope this help!

If I've understood your question, when the form is submitted, you want to query the database with the selected values.
Example using AND:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' AND make='%s' AND model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match those three values.
Example using OR:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' OR make='%s' OR model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match any of those three values.
You can read more about this:
mysql_query
mysql_real_escape_string
MySQL 5.6 Reference Manual :: 12 Functions and Operators :: 12.3 Operators

<select name="myFilter">
<option value="Chooseafilter" name="default">Choose a filter...</option>
<option value ="Lastname" name="opLastName">Last Name</option>
<option value="Firstname" name="opFirstName">First Name</option>
<select>
<li><!--TEXT SEARCH INPUT--><input type="text" name="search_filter" /></li>
...
dbconnection();#assume that all connection data is here
...
$filter = $_POST['myFilter']; #
...
switch($filter)
{
case "Lastname":
$selectedoption = "profile_name";
break;
case "Firstname":
$selectedoption="profile_first_name";
break;
case "Chooseafilter":
$selectedoption = "";
break;
}
$result = pg_query($db_con, "SELECT * FROM profile WHERE ".$selectedoption." LIKE'%$_POST[search_filter]%'");
$row = pg_fetch_assoc($result);
if (isset($_POST['submit']))
{
while($row = pg_fetch_assoc($result))
{
echo"<ul>
<form name='update' action='' method='POST'>
<li>Guest Last Name:</li>
<li><input type='text' name='profile_name_result' value='$row[profile_name]' /></li>
<li>Guest First Name:</li>
<li><input type='text' name='profile_first_name_result' value='$row[profile_first_name]' /></li>
<li><input type='submit' value='Update' name='update'></input></li>
...

Related

Update MySQL-database with array values

How can I update a database with the values from an array? For example, let’s say we got a database with three tables:
Meals:
mealnr(PK), name, sort
Ingredients: ingredientnr(PK), name, stock
Structure: mealnr(FK), ingredientnr(FK), amount
I filled the database with some meals and ingredients. Every meal consists of multiple ingredients. The chef decides you only need 75g of ingredient x instead of 100g for meal y, so it needs to be changed in the database. Of course it can be done with SQL-commands, but I want to do it using a form in PHP.
First I made a page where all the meals are displayed. A meal can be edited using the edit-button next to it and based on the mealnr, you can change the amount of one or multiple ingredients for that particular meal. On the edit-page all the ingredient names and amounts are displayed in a table. The amount fields are textfields, those can be edited.
I made this script, but I don’t know exactly how I can update my database with the values of an array. I tried it with a foreach-loop, but it doesn't work.. yet. Can somebody help me?
<?php
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db("eatit", $conn);
$id = $_REQUEST['mealnr'];
$result = mysql_query("SELECT meals.name AS mealname, structure.amount, ingredients.name AS ingredientname
FROM Meals, Structure, Ingredients
WHERE meals.mealnr = structure.mealnr
AND structure.ingredientnr = ingredients.ingredientnr
AND meals.mealnr = '$id'");
if(isset($_POST['save']))
{
$new_amount = $_POST['amount[]'];
foreach ($new_amount as $value) {
mysql_query("UPDATE structure SET amount ='$value', WHERE mealnr = '$id'")
or die(mysql_error());
}
}
mysql_close($conn);
?>
<p><strong>Ingredients:</strong></p>
<?php
echo "<table>";
echo "<tr>";
echo "<th>Ingredient</th>";
echo "<th>Amount (gr)</th>";
echo "</tr>";
while($ingredient = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>";
echo $ingredient['ingredientname'];
echo "</td>";
echo "<td>";
echo '<input type="text" formmethod="post" name ="amount[]" value="' . $ingredient['amount'] . '" />';
echo "</td>";
echo "</tr>";
}
?>
<input type="submit" name="save" value="save" />
In your HTML markup you have declared the elements holding the name amount as an array by using amount[].
So, in your php code that receives the data it's enough to just refer to the amounts this way:
$new_amount = $_POST['amount'];
instead of:
$new_amount = $_POST['amount[]']; // in fact, this is wrong
Your foreach is fine, you should add some checks so that the $value actually contains a value that you expect, for example an int, float or not less than zero (or whatever checks you find necessary).
foreach($new_amount as $value){
if($value != '' && $value >= 1){
//sql statements goes here.
}
}
Receiving form data this way and then directly injecting the result to your SQL statement is always dangerous:
$id = $_REQUEST['mealnr'];
If you declare that you expect an integer (as the id's should be) before you directly inject the code to your SQL statement you have already written safer code.
$id = (int)$_REQUEST['mealnr'];
Also, just for the record - the mysql_* library is deprecated. As pointed out in the comments, try using PDO or mysqli instead - really!

How to use checkboxes to retrieve specific data in a database

Lately i have been working on a form with which a user can select a checkbox and as a result of the selection it shows the database information in a table.
I browsed the stackoverflow questions and found a question that was almost the same, namely: Retrieve data from sql database and display in tables - Display certain data according to checkboxes checked
So with this information, and some other information from the web, i started to create my code. Though after completion i had several errors, namely my database fields were duplicate on output, the data that the field had isn't outputted and there were two warnings. After a lot of searching and editing/trying i couldn't find the right solution so hence me asking this question in here.
Before i display my code i first give some information about the checkboxes, database and table/fields (and a (small) note: it is a wordpress database).
I have 1 database called xxx_wp1. THis database contains various (wordpress) table's but the table i want to retrieve information from is called: wp_participants_database.
This table contains various columns (around 15). Though, for this testing example i used just 3 of the 15 columns named: authorss, research_source and research_title. I inserted some random information (3 rows) in these 3 columns.
The form i created has, kinda obviously, 3 checkboxes for each column (so 1 for authors, research source and title).
Based on the previous link and some wordpress information i started to create my code for the selection, it is as follows:
<form method="post">
<input type="checkbox" name="columns[]" value="1" /><label for="Authors">Authors</label><br />
<input type="checkbox" name="columns[]" value="2" /><label for="Research Source">Research Source</label><br />
<input type="checkbox" name="columns[]" value="3" /><label for="Research Title">Research Title</label><br />
<input type="submit" name="go" value="Submit"/>
</form>
<?php
$all = false;
$column_names = array('1' => 'Authors', '2'=>'Research Source', '3'=>'Research Title');
$column_entries = isset($_POST['columns']) ? $_POST['columns'] : array();
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
if (empty($sql_columns)) {
$all = true;
$sql_columns[] = "*";
} else {
$sql_columns[] = "authorss,research_source,research_title,";
}
global $wpdb;
//DNI CHECKBOX + ALL
$tmp = $wpdb->get_results( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database");
$result = mysql_query($tmp);
echo "<table border='1' style='width:450px'>
<tr>
<th>authorss</th>
<th>research_source</th>
<th>research_title</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['authorss'] . "</td>";
echo "<td>" . $row['research_source'] . "</td>";
echo "<td>" . $row['research_title'] . "</td>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
echo '</table>';
?>
<?php
mysql_close();
?>
As you can see, the quesry is a bit different because it has to connect to the Wordpress database (the global $wpdb and $wpdb->get_results). While typing this im thinking that this might also be part of the problem as this get_results is already getting results which i am also getting later on?
Anyway, while testing this i get a few errors / misbehavior which i cant seem to figure out.
The first errors are the following warnings:
- Warning: mysql_query() expects parameter 1 to be string, array given in /home/xxx/domains/mysite.nl/public_html/Recap/wp-content/themes/radiate/templates/pdb-search-new.php on line 32 --- which is this line of code: `$result = mysql_query($tmp);`
- Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in /home/xxx/domains/mysite.nl/public_html/Recap/wp-content/themes/radiate/templates/pdb-search-new.php on line 43 --- which is this line of code: `while( $row = mysql_fetch_assoc($result))`
The second problem is that all of the columns are echo'd TWICE even before submitting. So this would mean this line of code is being done no matter what:
if (empty($sql_columns)) {
$all = true;
$sql_columns[] = "*";
} else {
$sql_columns[] = "authorss,research_source,research_title,";
}
When i check a option and press the submit button, the right column is being showed (so yay that works), though all the 3 columns are still being showed (no matter what) as well as the selected one, so i got this if i select the first option:
authorss research_source research_title Authors (notice the first 3 are from my defined while the last one is from my defined $column_names.
The last problem is that the field values of the columns isn't being showed, the columns are just empty.
So the question is of anybody could give me some pointers about what is going wrong.
Thank you in advance!
*****UPDATE*****
I made some adjusting with the help of #Zeusarm
So firstly i changed the warnings (among others the $wpdb->get_results is changed to $wpdb->query) and the warnings are all gone. For some reason i gave the $array_names just their front-end names (stupid me), so i changed it, like you suggested to the proper column names as they are in the database table. So field 1,2,3 became: authors, research_source and research_title.
I also added the other changes. Although the errors are all gone, i still get all 3 the columns showed + 1 duplicate (depending on the number of checkboxes selected). Plus i still don't get the database data which is stored in the columns (for example: authorss has the following stored values in it: Barry, Henk and Nicolas.).
The code now looks like (with the form left out as it remained the same):
<?php
$all = false;
$column_names = array('1' => 'authorss', '2' => 'research_source', '3' => 'research_title');
if(isset($_POST['columns'])){
$column_entries = $_POST['columns'];
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
$sql_columns[] = "authorss";
$sql_columns[] = "research_source";
$sql_columns[] = "research_title";
} else {
$all = true;
$sql_columns[] = "*";
}
global $wpdb;
//DNI CHECKBOX + ALL
$tmp = $wpdb->query( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database");
$result = mysql_query($tmp);
echo "<table border='1' style='width:450px'>
<tr>
<th>authorss</th>
<th>research_source</th>
<th>research_title</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
if($result!==false && mysql_num_rows($result)>0){
while( $row = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td>" . $row['authorss'] . "</td>";
echo "<td>" . $row['research_source'] . "</td>";
echo "<td>" . $row['research_title'] . "</td>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
echo '</table>';
}
?>
<?php
mysql_close();
?>
*****UPDATE 2*****
So i changed the code and finally i am retrieving the data of the database! So i guess i should just work with the wordpress get_results for querying from now on.
Although i am retrieving the information i still have duplicates. When i go to the page, at first i have all 3 duplicates and the data retrieving is being output in the first 3 columns. When i select 1 checkbox option, the correct data of that checkbox is being displayed and the other data from the other checkboxes isn't (so that works). Though, for example when i only choose the authors checkbox, the data of authors is being displayed in the first authors checkbox and only 1 duplicate (namely 'authors') is being showed. Though when i click only the second checkbox, research source (column research_source) then the data of that column is only being showed (what is correct) BUT that data is being output in thew first authors column and again, 1 duplicate with the correct column name namely 'research_source'.
But because a picture says more than a 1000 words, i added some images to clear it up. (sorry for the links to the pictures but missing 2 reputation to post pics directly)
The starting columns/page (untouched):
Only authors selected and submitted:
Left this one out as i can also only upload 2 links withh less than 10 rep...
Only Research Source selected and submitted:
I see at least 2 errors in your code.
the $column_names associative array values are supposed to be passed as field names, so I assume that they are not correct, as you have spaces in them (and as I know wordpress by default does not have such field names.
if some selection is provided by user you are adding some extra field names to the once which are passed by user and you have a colon after them so it will generate an error.
I would rewrite the code like this
<?php
$all = false;
$column_names = array('1' => '`field1`', '2' => '`field2`', '3' => '`field3`');
if(isset($_POST['columns'])){
$column_entries = $_POST['columns'];
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
$sql_columns[] = "authorss";
$sql_columns[] = "research_source";
$sql_columns[] = "research_title";
} else {
$all = true;
$sql_columns[] = "*";
}
Also as you have said $wpdb->get_results returns already the results - array so that's why you get the errors. Plus before calling mysql_fetch_assoc it is better to check if the passed parameter is recource and if the number of rows is not 0.
if($result!==false && mysql_num_rows($result)>0){
while( $row = mysql_fetch_assoc($result)){
...
}
}
*********** UPDATE ***********
according to last changes try this code:
<?php
$all = false;
$column_names = array('1' => '`authorss`', '2' => '`research_source`', '3' => '`research_title`');
if(isset($_POST['columns'])){
$column_entries = $_POST['columns'];
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
} else {
$all = true;
$sql_columns[] = "authorss";
$sql_columns[] = "research_source";
$sql_columns[] = "research_title";
}
global $wpdb;
//DNI CHECKBOX + ALL
$tmp = $wpdb->get_results( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database");
echo "<table border='1' style='width:450px'>
<tr>
<th>authorss</th>
<th>research_source</th>
<th>research_title</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo "<td>" . $value . "</td>";
}
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
}
echo '</table>';
?>

Multiple checkbox values, which are retrieved from a database with a query, are not being displayed for an (unknown) reason

So lately i have been working on a way to post values from a database through checkbox selecting. Thanks to a previous question: How to use checkboxes to retrieve specific data in a database, i managed to get it working!
Although i got it working, i wanted to make my queries a bit more effective when multiple checkboxes are selected instead of writing queries with if/else for every checkbox possibility.
Through some research on stack overflow, this topic in particular: Run a query based on multiple checkboxes, i created the code for my own project. Though, for some reason it just wont output the data correctly, it even wont output anything at all.
So i looked in my code to see where stuff goes wrong. I passed in several echo's to get array information etc, but it all seems ok EXCEPT the last echo where i am echoing the query results (which returns 0).
So i am kinda stuck now since i cant figure out what goes wrong.
NOTE: It is for wordpress so that explains the little difference in querying.*
The code is as follows:
The HTML Code to display the checkboxes
<form method="post">
<div id="list1" class="dropdown-check-list">
<span class="anchor">Select Authors</span>
<ul class="items">
<li><input type="checkbox" name="columns[]" value="Barry" />Barry</li>
<li><input type="checkbox" name="columns[]" value="Henk" />Henk</li>
<li><input type="checkbox" name="columns[]" value="Nicolas" />Nicolas</li>
</ul>
</div>
<input type="submit" name="go" value="Submit"/>
</form>
The ID is for a Jquery dropdown effect.
The PHP code is as follows:
*The code below defines the column titles that are being displayed/echo'd in a table
$column_names = array(
"Authorss" => "Authorss",
"Research_Source" => "Research_Source",
"Research_Title" => "Research_Title"
);
$sql_columns = array();
foreach($column_names as $i) {
$sql_columns[] = $column_names[$i];
}
The next lines of code checks the checked checkbox values and queries the selected values:
if(!empty($_POST['columns'])) { // empty() checks if the value is set before checking if it's empty.
foreach($_POST['columns'] as $key=>$value){
// Runs mysql_real_escape_string() on every value encountered.
$clean_criteria = array_map('mysql_real_escape_string', $_REQUEST['columns']);
// Convert the array into a string.
$criteria = implode("','", $clean_criteria);
}
$tmp = $wpdb->get_results("
SELECT"
.implode(",", $sql_columns)."
FROM
wp_participants_database
WHERE
authorss IN ($criteria)
ORDER BY
authorss ASC
");
}
If non is selected the query selects all possible results (this still has to be created tho since i want the specific select query to work first):
else {
echo 'still needs to be edit to show everything here';
//$tmp = $wpdb->get_results( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database;");
}
Now comes the part where the queried data is being showed/put in tables:
echo "<table>
<tr>";
foreach($column_names as $k => $v) {
echo "<th>$v</th>";
}
echo "</tr>";
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
}
echo '</table>';
*****UPDATE*****
Got it fixed myself! First i deleted:
$column_names = array(
"Authorss" => "Authorss",
"Research_Source" => "Research_Source",
"Research_Title" => "Research_Title"
);
$sql_columns = array();
foreach($column_names as $i) {
$sql_columns[] = $column_names[$i];
}
This above code was unnecessary as the columns were all preset, so i just echo'd them by typing them out.
The problem was the following:
$tmp = $wpdb->get_results("
SELECT"
.implode(",", $sql_columns)."
FROM
wp_participants_database
WHERE
authorss IN ($criteria)
ORDER BY
authorss ASC
");
The $criteria variable should give a string to the IN, though in my code it was parsed as an literal (so no string). It seemed very easy, i just had to add the '' so it would be parsed as a string. Result: WHERE authorss IN ('$criteria')
<div>
<?php
$corpServicesValue = $row['corp_services'];
$value= explode(",",$corpServicesValue);
if(in_array("1",$value))echo '<input type="checkbox" name="corporationServices[]" value="1" checked >Management<br>';
?>
</div>

PHP echo out data into HTML drop drop down menu

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.

PHP Form from Array Select Value Edit/Save

I'm using an array to output a form for product entry.
$labels = array(
"category" => "Model",
"model_number" => "Model No.",
"description" => "Description");
The categories are populated as select/option set, which is easy when adding a new product. The issue comes when I need to edit the product. I would like to query the category table to return all the available categories to populate the select/option set. At the same time, I need to query the products table so that I can provide their saved Model Number and Description.
The following is my code from the add form to give you an idea of how I'm structuring this.
foreach($labels as $field => $label) {
if($field == "category") {
echo "<label>$label:</label>";
echo "<select name=\"$field\">";
while($row=mysqli_fetch_assoc($result)) {
extract($row);
echo "<option value=\"$category\">$category</option>";
}
echo "</select>";
echo "<br />";
}
else {
echo "<label>$label:</label>";
echo "<input type=\"text\" name=\"$field\" />";
echo "<br />";
}
Thanks for the help. I'm sure it's simple, but my brain isn't quite providing me with the solution at the moment.
Having $labels array is a bad idea.
Get all your data first. Select your product data into array. Select your categories into array.
Show the form, as any other HTML you create with PHP
<label>Model:</label>
<select name="category">
<? foreach($cats as $category): ?>
<option<? if ($category == $row['category'])?> selected?>><?=$category?></option>
<? endforeach ?>
</select>
<br />
<label>Model No.:</label>
<input type="text" name="model_number" value="<?=$row['model_number']?>"/>
<br />
and so on
don't forget to htmlspecialchars() your values before placing them into value attribute
you can query the product table like this:
$sql = "SELECT * FROM products WHERE product_id = $product_id";
$q = mysql_query( $sql );
$row = mysql_fetch_assoc( $q );
$model_number = $row['model_number'];
$description = $row['description'];
$category = $row['category'];

Categories