Define HTML check boxes from database values - php

I have project with HTML PHP and SQL database. I designed HTML input form to collect data from user and put drop down menu using PHP. It collected data from SQL database using query and those data used to drop down list and user can select those data. I have using following codes in PHP section.
$query2 = "SELECT Name FROM class ORDER BY Name";
$results2 = mysqli_query($connection, $query2);
while($result = mysqli_fetch_array($results2))
{
$Classes .= "<option value=\"{$result['Name']}\">{$result['Name']}</option>";
}
In my database there are several classes as Class_A, Class_B, Class_C and etc. (Admin can create new class or delete available class. Then when user select classes, showing classes can be different according to Admin's settings.)
In HTML form section I used following code to display Class names.
<p>
<label for=" ">Classes Are</label><br>
<select name="Classes[]" size="3" multiple >
<?php echo $Classes ?>
</select>
</p>
I tried to use this process through Check boxes (replace Drop down list from Check boxes) But I cant fix that. So, If someone can give proper way to do this it is highly appreciate.

Perhaps this is what you need to use checkboxes? The name assigned to the HTML input element uses an array type syntax with the name of from the db supplied
$sql = "select `name` from `class` order by `name`";
$res = $connection->query( $sql );
while( $rs = res->fetch_object() ) {
$classes=sprintf(
'<label>%1$s:
<input type="checkbox" value="%1$s" name="Classes[%1$s]" />
</label>',
$rs->name
);
}
Then, to process the form submission once the user has selected one or more checkboxes you could do:
foreach( $_POST['Classes'] as $index => $value ){
// do things...
}
You likely do not even need to add the name so perhaps simply Classes[] as the input name would suffice. Please clarify the issue you had when trying to use checkboxes rather than select menus.

Related

Assign and return select option dynamically?

I have a form select which is generated based on results returned from a mysql query.
Q1) How do I assign a name identity (integer value) based on the teamID pull out of the database?
Q2) How could I then get the option selected and add it to a php variable which could then be used to update a table based on the users selection?
Below is the code I have so far for creating the dynamic drop down list, which get the results out of the database.
<?php
$data= mysql_query("SELECT * FROM teams
WHERE teamID NOT IN (
SELECT TeamID
FROM leagueInformation
WHERE leagueID = 1
)
") or die(mysql_query());
echo "<select name=\"team\" class=\"col-lg-12\" style=\"padding:10px; background:#e1e1e1;\">\n";
while($info = mysql_fetch_array( $data ))
{
$teamID = $info['teamID'];
echo "<option name=" . $team . " value=" . $teamID . ">" .$info['teamName'] . "</option>";
}
echo "</select>\n";
?>
Q1) How do I assign a name identity (integer value) based on the teamID pull out of the database?
This question is not so clear, but I think this is what you are trying to do?
<?php $data= mysql_query(
"SELECT * FROM teams WHERE teamID NOT IN (
SELECT TeamID
FROM leagueInformation
WHERE leagueID = 1)
") or die(mysql_query());
?>
<form name="teams_form" method="POST">
<select name="team" class="col-lg-12" style="...">
<?php while($info = mysql_fetch_array( $data )): ?>
<option value="<?php echo $info['teamID'] ?>">
<?php echo $info['teamName'] ?>
</option>
<?php endwhile; ?>
</select>
</form>
Q2) How could I then get the option selected and add it to a php variable which could then be used to update a table based on the users selection?
First you will need to wrap your select inside a form (like I did), then you can check the selected value like this:
if(isset($_POST['team']) && !empty['team']){
$selected_team = $_POST['team'];
mysql_query("Do what you want with the selected team");
}
Some notes about your code:
Avoid to use mysql_*, use mysqli_* or PDO, and always prevent SQL injections
<option> tags don't have name properties, and in this case $team is not defined
Embed PHP inside HTML, not HTML in PHP.
Your first question doesn't make sense to me yet, I'll update the answer when it does.
When the user submits the form, you can get the option selected using the $_GET or $_POST (depending your your form's method) variables.
Like this:
$teamId = $_POST['team'];
put everything in a <form/> with an action pointing to the page, and a method (get or post), then in the script get the variable by the <select/> name value reading $_GET or $_POST variables, and I quote the comment about the "name" in option as invalid attribute.

PHP. Display content of SQL table based on selection chosen in dropdown box

Sorry if this has been asked and answered but I have looked and can't see it anywhere. Yes I am a nooby.
I have a DB with 3 tables: flour, filler and others.
What I would like to do is have a dropdown List. So, if user chooses flour from the Drop Down box it will display flour table. If the user chooses filler then filler table be displayed.
Hope this is clear. I hope you can help. Thanks in advance.
<Form id="form1" name="form1" method="get" >
Supplies of
<select name=filler action="flour.php">
<option value="1" selected>flour</option>
<option value="2">filler</option>
<option value="3">others</option>
</select>
<input type="submit" value="Submit" />
</form>
<?php
header("Content-Type: text/html; charset=windows-1251");
#mysql_connect('localhost','root','');
#mysql_select_db('krendel');
#mysql_query('SET NAMES cp1251');
$res = mysql_query("SELECT * FROM `flour` ") or die(mysql_error());
$res2 = mysql_query("SELECT * FROM `filler` ") or die(mysql_error());
$res3 = mysql_query("SELECT * FROM `addit` ") or die(mysql_error());
Add the action to the form, not select element. So you'd have
<form method="get" action="flour.php">
and
In your form processing script (flour.php), you could so something like this:
switch($_GET['filler'])
{
case '1':
$table = 'flour';
break;
case '2':
$table = 'filler';
break;
case '3':
default:
$table = 'addit';
}
$res = mysql_query("SELECT * FROM {$table}");
If all tables have the same structure, consider combining the tables, and adding a type column (varchar containing either flour, filler, or addit for simplicity).
you could then write the query like this (still using the $table variable name to work with the code above.
$res = mysql_query("SELECT * FROM table WHERE type='{$table}'");
Using mysql_query, and concatenating variables into the SQL is not good practice now - have a look at PDO and parameterised queries as you learn more.
Some quick and dirty display code:
<?php
$results = array();
while($row = mysql_fetch_array($res, MYSQL_ASSOC)) { ?>
$results[] = $row;
}
?>
<table>
<?php foreach($results as $result) { ?>
<td><?php echo $result['column_name'] ?></td>
<?php } ?>
</table>
This should get you started - as I said above, it's quick and dirty. You'll be able to improve upon this as you get more knowledge (properly separating out the HTML from PHP, for example - it's really worthwhile reading up on MVC amongst other patterns).
Just don't use this code on a production system!
Hope this helps.
The page that is going to display the table needs to check the $_GET['filler'] and see what the value is. Since you are using $_GET and a drop box, you should have a white list something like: $filler_white_list = array('flower', 'filler', 'other');
Check to see if the value of $_GET['filler'] is in the $filler_white_list array. If the $_GET['filler'] value is valid, then make your query:
$res = mysqli_query('SELECT * FROM '.$_GET['filler'].';') or die(mysqli_error());
Then loop through the result set to print out to the page:
while($row = mysqli_fetch_array($res)){
//get the columns by using $row['column_name']
//decide how you want to format
}
Things to note: I used mysqli instead of mysql, because the mysql is deprecated (no longer supported), The SELECT statement uses an *, but it is better to list out the names of the column since it is faster. It is not a good idea to use the the values of the drop box as the name of you tables in the database. The less information you reveal about your database, the better. Of course, if this is not for a production DB, then it doesn't matter. But, I think it is always best to think about security even when you're just practicing. Also, I put the $_GET['filler'] in the middle of the SELECT statement because the table's names are the same as the drop box.

Passing value from a dropdown list from one php to another

I have
A dropdown list populated from a MySQL table.
A button.
Another php page
What I need to do:
On clicking the button, pass the value selected from the dropdown list as a variable to second php page.
Pass that variable into a mysql query on the second php page. eg: $result = mysql_query("Select * from table where name like "$drop_down_value");
I am new to php and pardon my naivety.
This is my code to get values for the dropdown list:
function dropdown_query()
{
mysql_connect("localhost","root","root") or die("Failed to connect with database!!!!");
mysql_select_db("student_test") or die("cannot select DB");
$result = mysql_query("Select * from marks");
if($result=== FALSE){
die(mysql_error());
}
while($r=mysql_fetch_array($result))
{
echo '<option value="' .$r['marks'] . '">' . $r['marks'] . '</option>';
}
and this is my HTML part:
select name="dropdown" onchange="somefunc()">
<option value="">Select...</option>
<?php dropdown_query()?>
</select>
Lets say I use a similar query on another php. But would use the value selected on this page as a variable in that query.
By wrapping the drop down in a form with POST method, you can send the value to the next page and retrieve via $_POST['your_field_name']. See the docs.
Your page1 will have a form something like
<form action="page2.php" method="post">
<p>Name: <input type="text" name="name" /></p>
<p><input type="submit" /></p>
</form>
And in page2.php you can do something along the lines of
$name = $_POST['name'];
$sql = "SELECT * FROM table WHERE name LIKE '$name'";
...
(But make sure to scrub the user input before using it on page2.php!)
you will need javascript to do this. The page already finish loading. php script wont work after page finish loading. try jquery, ez to use
The answer to your question is to use the $_POST or $_GET superglobal variables in PHP. You can use either of these to obtain the value of the dropdown list from the first page after the button is clicked. For example, you could use the following code to obtain the value of the dropdown list:
$drop_down_value = $_POST['dropdown'];
Then, you can pass this variable into your MySQL query on the second page, as you have outlined in your question:
$result = mysql_query("Select * from table where name like "$drop_down_value");

Processing a form created by dynamic php/mySql Setup

I run a script to create an order form, this is just a really small sample. I'm not so good with PHP and dynamic forms. It pulls data from mysql database.
<td>
<h3>Round Cuts</h3>
<?php while($row = mysql_fetch_array($round_cuts)){
$round_box_value = #$row["meat_names"];
$round_box_value_name = #$row["meat_names"];
echo " <input type=\"checkbox\" name=\"round_box_value\" value=\"$round_box_value_name\"> $round_box_value_name";
echo "<br>";
}?>
</td>
I've ever really only built basic contact forms, how could I process a dynamic form like this. If all else fails I would just take all the possible elements and program this like it was a not dynamic. There must be a better way though.
Even a link to a website would be helpful. I've been searching for a solution. Thanks.
I'll assume your table as a primary key of id
Start off with a minor change to your checkboxes:
<?php
while($row = mysql_fetch_array($round_cuts)){
echo sprintf('<label><input type="checkbox" name="round_box_value[]" value="%s"> %s</label><br>', $row['id'], $row['meat_names']);
}
?>
The name now has an [] at the end to tell php it's an array of values + I've wrapped the checkbox in a label for convenience.
Then when you process the form, you can simply iterate through round_box_value like so
<?php
foreach ($_POST['round_box_value'] as $id) {
// $id is the table reference from your previous table
}
// or query all the rows selected
$ids = array_map('intval', $_POST['round_box_value']); // "basic" sql injection handler
$sql = "SELECT * FROM table WHERE id IN (".implode(",", $ids).")";
should produce something like:
SELECT * FROM table WHERE id IN (2,5,7)

how to get php to read in a string of words from a dropdown box?

Can any one please help me? I am new to php, currently I am trying to use $_POST['item'] to obtain a string (consists of many words) from a dropdown box and then process it. However, when I use $_POST['item'], only first word is returned, the rest of words are missing.
I have a dropdown box, something like:
echo "<form action='process_form.php' method='post'>";
echo "Select an item<br />";
echo "<select name='item' id='item'>";
...
...
...
each item in the dropdown box is a string that has product names like:
dressmaker mannequin size 12
torso mannequin in white color
...
User will then select an item from the dropdown box. When I used $_POST['item'] to obtain this string, I get the first word "dressmaker", all the rests were missing.
How do I get the whole string?
Many thanks in advance.
I am not sure exactly what you are doing but I would do something like this. For this example I assume that the values "dressmaker mannequin size 12" will correspond to the values of the columns in the database to which I will refer to as "colA, colB, colC, and colD", and in addition I assume you have an "ID" column in your database.
Here is the code I would use to generate the select drop-down list:
//$query is the variable storing the result of the mysql_query();
//assumption is that the result-set is non-empty
echo '<select name="item" id="item">\n'; //\n - new line character
//run through the loop to generate the items inside the list
while ($result = mysql_fetch_assoc($query)) {
//note the id - it will be used to find data in the
//database after the POST is complete
//couple of temp variables (not necessary but makes code cleaner)
$database_id = $result["ID"];
$colA = $result["colA"]; //ex:dressmaker
$colB = $result["colB"]; //ex:mannequin
$colC = $result["colC"]; //ex:size
$colD = $result["colD"]; //ex:12
//add option to the select drop-down
echo "<option value=\"$database_id\">$colA $colB $colC $colD</option>\n";
}
echo "</select>";
Now to retrieve the data from the POST. I am including the code Drewdin suggested.
//form was submitted already
//assumption is that the database connection is established
$item_id = mysql_real_escape_string(trim($_POST["item"]));
//Now get the info from the database for this id
//table is "table"
$string = "SELECT * FROM table WHERE ID = $item_id";
$query = mysql_query($string) or die("Could not complete the query: $string");
//assumption here is that the result set is non-empty
$result = mysql_fetch_assoc($query);
$colA = $result["colA"]; //ex:dressmaker
$colB = $result["colB"]; //ex:mannequin
$colC = $result["colC"]; //ex:size
$colD = $result["colD"]; //ex:12
//now you can use the values of colA-D to compute whatever you want
Hope this helps. Using database ids is nice for security plus it makes things more manageable.
Regarding using this blog. You can post comments to the answers people post. If you want however to add something to your question, you can edit your original question and just make sure its obvious what was added.
When the issue is resolved and if any answer helped and you liked it, you can pick it as the final answer by clicking the check mark next to it.
Best of luck
without seeing your select options i think this might help you
if (isset($_POST['submit'])) {
// Grab the output of the select list
$Select_Output = mysqli_real_escape_string( $dbc, trim($_POST['item']));
//What ever else you want to do here...
}
I also would use Miki725's post to make sure your select list is setup correctly
This is how the php gets the values from the HTML select item:
<select name="item" id="item">
<option value="this is option 1">option 1</option>
<option value="this is option 2">option 2</option>
<option value="this is option 4">option 3</option>
...
</select>
Basically you would do something like:
$var = $_POST['item'];
The $var will be the whatever was entered into the "value" of the option tag. So just make sure you have the proper values entered into the value fields.
Hope that helps.

Categories