Populate Table from more than one drop-down list - php

I'm trying to populate a Table after a user picks options from a drop down list when this options are picked the table should be populated based on selected options. I'm not sure how can I get this done and I've searched for tutorias etc but nothing helped me. So I'll be glad if someone can help somehow for example with small test codes etc.
I'm using PHP and the options for the drop-down list come from a MySQL-Database so in summary a person will choose a user from Users-drop down list after that a another option from different drop down list and then there's also going to be a date filter after 1, 2 or all 3 are selected a table will be produced based on the selected values.
So far I've no code done because I have no idea how to do it but I guess I need to put all 3 dropdown lists in a form and after submission I should produce the table, but how can I have more than one <select> ..... </select> in a <form> and submit them all simultaneously.
What I've done so far (I know it's unsafe and that mysql_* doesn't exist anymore in PHP7) but please don't criticize it.
UPDATE
//Database query for User drop-down(DD) population.
$sqlDD = " SELECT DISTINCT `user` FROM `users` " ;
$resultDD = mysql_query($sqlDD);
//Database query for Status drop-down(DD) population.
$sqlDDStatus = " SELECT `status` FROM `status` WHERE `id` = 1 OR
`id` = 123 OR `id` = 182 OR `id` = 12 ";
$resultDDStatus = mysql_query($sqlDDStatus);
<form id="form1" name="form1" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<select name="userSelect">
<?php
while($rowDD = mysql_fetch_array($resultDD)):
echo "<option value='" . htmlspecialchars($rowDD['user']) ."'>" . htmlspecialchars($rowDD['user']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<!-- Second DD-list in the same form -->
<select name="Status" style="max-width: 250px;" >
<?php
while($rowDDS = mysql_fetch_array($resultDDStatus)):
echo "<option value='" . htmlspecialchars($rowDDS['status']) ."'>" . htmlspecialchars($rowDDS['status']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<input type="submit" name="submit" value='Find'/>
</form>
//Get the submited data
<?php if(isset($_POST['submit'])): ?>
<?php echo 'This is submitted ' . $_POST['submit']; ?>
<?php endif; ?>
I've added echo 'This is submitted ' . $_POST['submit'];
because i wanted to see what is submitted but all it get's echoed out is only
"Find".
Any ideas how can i get the data submitted from both 's in the form and populate a table based on it ?
UPDATE 2
After getting an answer from other users I saw that my forms handles the data correctly but my question now is how can I use the data from the Submitted DDL Form and populate a table with them? So far I've tried the following:
<?php if(isset($_POST['submit'])): ?>
<?php $result = mysql_query( "SELECT * FROM `users` WHERE `user` =
$_POST['userSelect'] AND (`id` = 1 OR `id` = 18)" );
?>
<?php endif; ?>
and then in the table
<table>
<?php while ($row = mysql_fetch_assoc($result)) :; ?>
<tr>
<td><?php echo $row['user']; ?></td>
<?php endwhile; ?>
</table>
But I just don't get any response when I try it. How can I fix my problem and get the wanted output?
EDIT
I think that i've found my mistake after some research im not able to test the code now but i'm almost positive that you can't use $_POST['userSelect'] in the Database query so i just need to assign $_POST['userSelect'] to some variable before i use it in the query. So far i've gotten useful 1 little useful tip...... so disappointed from stackoverflow .......

This is a basis HTML/PHP page for getting data from the backend to the frontend, this should get you started. Try to print the data (in the while loop on the HTML page).
<html>
<head>
<title></title>
</head>
<body>
<form action="dropdown.php" method="POST">
<select name='options'>
<option>option 1</option>
<option>option 2</option>>
<option>option 3</option>>
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}else{
if (!empty($_POST)){
if(!empty($_POST['options'])){
$option = $_POST['options'];
$query = "SELECT * FROM table WHERE option='$option'";
$res = $mysqli->query($query);
while($data = $res->fetch_assoc()){
//print data to HTML page
print_f('%s, $s\n', $data['firstname'], $data['lastname']);
}
}
}
}
?>

Your form is probably working, the reason you only get "Find" is because you are printing the value of the submit button.
To get an overview of your form data, try:
echo '<pre>';
print_r($_POST);
echo '</pre>';
You will get the other values of your form by using the name attribute of your <select> with $_POST:
echo $_POST['userSelect'];
echo $_POST['Status'];
By the way, you are using a deprecated extension (written here for example), it is recommended to use MySQLi or PDO (especially PDO is recommended). If you are working with PHP 7, mysql_connect won't work as it has been removed.
And I'm not sure the use of htmlspecialchars() is relevant on each database data you use.
PHP.net - print_r() (See also var_dump())
PHP.net - $_POST

Related

Populate select field from SQL, use select to update database

I am practicing with developing a little bit but I stumbled upon a small issue which I just cannot get my head around. The goal is simple: users fill out a form and are then redirected to either the results page or the form. From the results page, users can navigate to a page where they can edit any records that match the time period and the name they enter.
Example: User 1 adds a car named 'Banshee', is redirected to the results page, sees the 'Banshee' car but then decides he wants the color to be different. The user navigates to the update page and is able to either type in 'Banshee' or select 'Banshee' from a dropdown list. The first option works but the latter is the solution I'm looking for.
Currently I have the following form (this is just the part that matters):
<form method="post" name="input" action="edittest.php" >
<?php
include("/var/www/html/includes/sqlconnecttest.php");
$db=mysqli_select_db($connect,$database)
or die("Could not connect to the database");
$query = "SELECT * FROM cars WHERE datetime > DATE_SUB(CURDATE(), INTERVAL 5 DAY);";
$sql = mysqli_query($connect,$query);
?>
<p>
<label>Name</label>
<select name="name" form="input" required>
<?php
echo "<option value=\"\" disabled=\"disabled\" selected=\"selected\" style=\"display\:none\"></option>";
while ($row = mysqli_fetch_array($sql)){
echo "<option value=\"name\">" . $row['name'] . "</option>";
}
?>
</select>
</p>
The connection is done through the following PHP code:
<?php
include("/var/www/html/includes/sqlconnecttest.php");
$db = new mysqli("$host","$user","$pass","$database");
$name=$_POST['name'];
$stmt = $db->prepare("UPDATE cars
SET color=?, airco=?, tires=?, rims=?, price=?, engine=?, remarks=?
WHERE name='$name' AND datetime > DATE_SUB(CURDATE(), INTERVAL 5 DAY);");
$stmt->bind_param('ssssiss', $ccolor, $cairco, $ctires, $crims, $cprice, $cengine, $cremarks);
$color=$_POST['color'];
$airco=$_POST['airco'];
$tires=$_POST['tires'];
$rims=$_POST['rims'];
$price=$_POST['price'];
$engine=$_POST['engine'];
$remarks=$_POST['remarks'];
$ccolor=htmlspecialchars($color,ENT_QUOTES);
$cairco=htmlspecialchars($airco,ENT_QUOTES);
$ctires=htmlspecialchars($tires,ENT_QUOTES);
$crims=htmlspecialchars($rims,ENT_QUOTES);
$cprice=htmlspecialchars($price,ENT_QUOTES);
$cengine=htmlspecialchars($engine,ENT_QUOTES);
$cremarks=htmlspecialchars($remarks,ENT_QUOTES);
if ($stmt->execute()) {
header("Location: redtest.php");
}
?>
The issue is as follows: when I use the above posted HTML form with the while-loop populating the options, the update page doesn't do anything. No errors, no updates it just performs the action (open edittest.php).
However, when I replace the above posted dropdown menu with this simple textfield, it works fine. Whatever I type in the textfield, it uses it in the update query.
<p>
<label>Name</label>
<input type="text" maxlength="50" name="name" required />
</p>
I've got the feeling that the PHP code breaks the connection between the select-field and the rest of the form.
I see two issues with your select. First you have what appears to be a default value that you're then hiding with display:none. You're also setting the same value for every option. I believe this is what you're trying to do.
<select name="name" form="input" required>
<option value=""></option>
<?php
while ($row = mysqli_fetch_array($sql)){
echo "<option value=\"". $row['name'] ."\">" . $row['name'] . "</option>";
}
?>
</select>

populating a value field of a combo-box from a MySQL query

This question is relating to a problem that a previous questions answer yielded! (as is the way)
I have set up a simple script to access a MySQL database and populate a dropdown combobox with usernames, but it wont accept the values from my php, it creates the names however so its some form of syntax error but not one that causes a crash.
<?php
# parameters for connection to MySQL database
$hostname="";
$database="";
$ausername="";
$apassword="";
mysql_connect ("$hostname","$ausername","$apassword");
mysql_select_db ("$database");
$query = mysql_query("SELECT DISTINCT username FROM dbusers") or die(mysql_error());
?>
<div id="select_users" style="position:absolute;width:466px;height:108px;">
<form name="select_user" method="POST" action="./page5.php" id="Form1">
<div id="select_a_user" style="position:absolute;left:0px;top:20px;width:100px;height:20px;z-index:11;text- align:left;">
<span style="color:#000000;font-family:Arial;font-size:15px;">Select User</span></div>
<select name="users[]" multiple = "multiple" id="users" style="position:absolute;left:93px;top:15px;width:200px;height:75px;z-index:12;">
<option value="test"> Select a user</option>
<?php
while($row = mysql_fetch_assoc($query)){
$username = $row["username"];
?>
<option value= <?php $username ?> > <?php echo $username ?> </option>
<?php
}?>
</select>
<input type="submit" id="Button1" name="" value="Submit" style="position:absolute;left:93px;top:100px;width:96px;height:25px;z-index:13;">
</form>
</div>
the section
<option value= <?php $username ?> > <?php echo $username ?> </option>"
is what is causing the issue i think as its not assigning the variable value
Im using the following script to debug and display what is supposed to be inside the array after POST
<?php
if(isset($_POST['users']))
{
$ausers = $_POST['users'];
if(!isset($ausers))
{
echo("<p>You didn't select any users!</p>\n");
}
else
{
$nusers = count($ausers);
echo("<p>You selected $nusers user: ");
for($i=0; $i < $nusers; $i++)
{
echo($ausers[$i] . " ");
}
echo("</p>");
}
}
?>
It will output the number of data files in the array but wont display their content, which after force echo'ing the variables has lead me to believe that the values of the array are all empty.
The end result of this selection is to store each entry of the array as a variable for another MySQL query if that any help with the correct code to achieve the result.
Thanks!
<option value= <?php $username ?>
^----you forgot 'echo' here
No echo, no output, and your generated html becomes
<option value=>foo</option>
I am not sure what the issue is here, sometimes when dealing with a database though it will create a multidimensional array. If this is the case you aren't actually looking at any values. To help you check try doing a var_dump on the variable to see everything about the data. It will even tell you if it is truly empty it should look like this:
echo var_dump($varName);
That should help you with debugging and maybe help you post some better information.

How can I save the selected item from an HTML select in a PHP variable?

I have an HTML select where the drop down list is created from a SQL query.
I'm wondering how I can then save the item that the user selects into a PHP variable that I can pass on to other PHP pages.
Thanks.
<tr>
<td>DRM Staff List</td><span class="required">*</span>:<br />
<td>
<select name="unit">
<?php
$conn = oci_connect("username", "password", "url");
$sql = 'select distinct "DRM Primary" from GIS_DATA_LOAD where "DRM Primary" is not null order by "DRM Primary" asc' ;
$stid = oci_parse($conn, $sql);
$success = oci_execute($stid);
echo $success;
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC))
{
echo "<option value=\"unit1\">" . $row['DRM Primary'] . "</option>";
}
?>
</select>
</td>
</tr>
Add you code inside the form tag as below and make a form submit action ($_POST or $_GET) using javascipt as onselect.
Since the code is on client side so you have to for sure submit it to the server to save the selected option in a php variable.
<tr>
<td>DRM Staff List</td><span class="required">*</span>:<br />
<td>
<form action="" method="POST" name="myform">
<select name="unit" onchange="this.form.submit()>
<?php
$conn = oci_connect("username", "password", "url");
$sql = 'select distinct "DRM Primary" from GIS_DATA_LOAD where "DRM Primary" is not null order by "DRM Primary" asc' ;
$stid = oci_parse($conn, $sql);
$success = oci_execute($stid);
echo $success;
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC))
{
echo "<option value=\"unit1\">" . $row['DRM Primary'] . "</option>";
}
?>
</select>
</form>
</td>
</tr>
// now to save the submitted form as value in a php we will use the following code
<?php
if(isset($_POST['myform']))
$selected_unit=$_POST['unit'];
?>
you can also use onselect() function ... not sure about that..
Hope it helps..thanks :)
You might want to set a unique value for each option, else there's no telling which option was actually selected.
When you submit the form PHP will internally generate a super global array. This, as it sounds, is global and can be accessed anywhere within the script execution via variables:
$_POST
$_GET
So after submitting your form, if it is a HTTP post request then you should find your value like this:
echo $_POST['unit']; // Unit 1 etc
There are other 'superglobals'. See the documentation for more information.
Its not possible to set a variable from client side.
Using AJAX to submit the form may help. It won't require the page reload.

Display result in dropdown and select to perform query in php mysql

I have a database named Data which has a table in which their are different names of products their id and prices, i want to make a web page using php so that i can edit,add and save the items from the web page to the DB and search the names accordingly.
<html>
<head>
<title>Products store</title>
</head>
<body>
<p style="font-size:20px" align="center"> <b>Product Database Editor</b> </p>
<p>
<form method="post">
Enter Product Name: <input type="text" name="pname" id="pname" size="70">
<input type="submit">
</p>
<form method="post">
<select id="opt" name="opt">
<?php
$pname = $_REQUEST['pname'];
// $pname= mysql_real_escape_string($_POST['pname']);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Dataentry", $con);
$result = mysql_query("SELECT * FROM products where name like '%$pname%'");
$result_rows = mysql_num_rows($result);
if($pname==NULL)
{
echo "Please enter a product name!";
}
else if($result_rows==0)
{
echo "Product Name does not exist!";
}
else
{
while($row = mysql_fetch_array($result))
{
$name = $row['name'];
echo "<option value='$name_selected'>$name</option>";
//echo ("<option value = '" . $row['name'] . "'>" . $row['id'] . "</option>");
echo $name_selected;
echo "<br />";
}
}
mysql_close($con);
?>
</select>
</form>
</body>
</html>
when i run this code i get the names list in the dropdown but after i select any name, nothing happens, how should i modify my code so that i can select any name from the dropdown and then be able to fetch the price of that particular name to edit it.
please help, coding will be much helpful.
Suppose you have a question like this in your dropdown menu.
Q - How many colors does the US flag has?
Now, from what I understand you want your choice from the drop down menu to appear instantly..
Well, here is a simple select form.
<form method="post">
<select id="opt" name="opt">
<option value="four">four</option>
<option value="five">five</option>
<option value="two">two</option>
<option value="million">million</option>
</select>​
And, the JS code:
$(document).ready(function() {
$("#opt").change(function() {
alert($(this).val());
});
});​
Now, click her a DEMO with jsFiddle to show you, how it works.
You can copy/paste the codes and include them in your site, this is a simple code, but you if you small knowledge of Javascript you can manipulate the data the way you need it to appear. .
To get a value of an input (this case, from a dropdown) on the fly, you need to use client-side scripting language javascript (or jquery) and use ajax to sent it to server-side, where the code is in PHP.

how can i view the data resulting from one of the choices in the dropdown list?

im new to php so im having some problems creating what i want
i'll explain first what i need .. there conferences, each conference has a list of reviewers and authors.
i have create a dropdown list where the user chooses which conference ... i want to show a list of the reviewers and the authors that are in this conference after clicking submit.
that is my code
<?php
$con = mysql_connect("localhost:3306","root","");
mysql_select_db("messaging_dd", $con);
$sql_drop = "SELECT conference_ID,conference_name FROM Conferences";
$drop_result = mysql_query($sql_drop,$con) or die(mysql_error());
$num_rows = mysql_num_rows($drop_result) or die(mysql_error());
mysql_close($con);
?>
<form name="choose" action="savedata.php" method="POST">
<br />
Conference: <select name="conference">
<?php
for($i=0 ; $i<$num_rows ; $i++)
{
$idofconference = mysql_result($drop_result,$i,0);
$nameofconference = mysql_result($drop_result,$i,1);
echo '<option value=" '.$idofconference.' ">'.$nameofconference.'</option>';
}
?>
</select>
<br />
<input type="submit" value="submit" name="submit" />
</form>
Try this,
$conf_id = $_POST['conference'];
$con = mysql_connect("localhost:3306","root","");
mysql_select_db("messaging_dd", $con);
$sql = "SELECT review, author FROM Reviews WHERE conf_id = ".$conf_id;
$review_list = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
Or you can go for Ajax. Updating your search result, without reloading the whole page. Reference for Ajax: http://www.w3schools.com/php/php_ajax_database.asp
All the data being submitted gets stored in the $_POST variable as an array. Your conference ID will be in $_POST['conference'] as the name of your select element is conference.
An other approach is to load the desired data (reviewers and authors) through an AJAX request so that the viewer of your website won't leave the webpage.
it's similar to what you have done, just add conference id details like this:
$sql = "SELECT reviewer, author FROM Conferences where conference_ID = " . $_POST['conference'];
In your file savedata.php you can put
$whatever = $_POST['conference']
$_POST is one of several arrays in php that is reserved for system data, for example you can make calls to $_server to find out details about the server(eg the time on the server)
you could also change the method='POST' to method='GET' and it would be in the GET array
$whatever = $_GET['conference']
this is a bit less secure, but if that's not a priority its worth considering
I think you should Try this.
<form name="choose" action="savedata.php" method="POST">
<br />
Conference: <select name="conference">
<?php
while($row=mysql_fetch_array($drop_result)
{
echo '<option value=" '.$idofconference.' ">'.$nameofconference.'</option>';
}
?>
</select>

Categories