This question already has answers here:
Populate drop down list from MySQL column data
(2 answers)
Closed 7 years ago.
so I want to make a drop down list in my form but rather than manually writing the options in the form I want to link it to my database.
HTML
<form>
<select name="fruit">
<option value="apple">Apples</option>
<option value="banana">Bananas</option>
<option value="pear">Pears</option>
</select>
<input type="submit" value="Submit">
</form>
This is what I have so far but I want to exclude the option values and replace them with existing records in my database. How do I do this in PHP?
I know I will be using something like, but I'm not sure
$results = $pdo->query('SELECT * FROM fruit');
foreach ($results as $row)
Thanks for the help :)
Assuming that your fruit table has name field:
<form>
<select name="fruit">
<?php
$results = $pdo->query('SELECT * FROM fruit');
foreach ($results as $row):
?>
<option value="<?php $row['name']?>"><?php ucfirst($row['name']) . "s"; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="Submit">
</form>
<form>
<select name="fruit">
<?php
$conn = new PDO("mysql:host=localhost;dbname=database", 'username', 'password', array( PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$results = $conn->query("SELECT * FROM fruit");
while($row = $results->fetch( PDO::FETCH_ASSOC )){
?>
<option value="<?= $row['id'] ?>"><?= $row['fruitname'] ?></option>
<?php
}
?>
</select>
<input type="submit" value="Submit">
</form>
This should give you a basic idea of how to do this.
In your case this is the solution:
<form>
<select name="fruits" class="form-control">
<?php
$results = $pdo->query('SELECT * FROM fruit');
foreach ($results as $row)
{
?><option value="<?= $row['id'] ?>"><?= $row['fruitname'] ?></option><?php
}
?>
</select>
<input type="submit" value="Submit">
</form>
Related
I have a form with many multiple select lists. There are several multiple select lists(blocks) in the form. How can I submit the multiple select data to the database?
I have tried to create a foreach statement but the problem is it only submits one option in the database.
<?php
$db = mysqli_connect('localhost','root','','trial') or die($db);
if (isset($_POST['submit'])) {
$marks = mysqli_real_escape_string($db,$_POST['marks']);
$subjects= $_POST['subject'];
$farming= $_POST['farming'];
foreach ($subjects as $i) {
$subject = $i;
$sql = "INSERT INTO `trial_table` (`subjects`, `marks`) VALUES ('".mysqli_real_escape_string($db,$subject)."', '$marks')";
mysqli_query($db,$sql);
}
$sql1 = "INSERT INTO `trial_table` (`marks`) VALUES ('$marks')";
mysqli_query($db,$sql1);
}
?>
<body>
<form method="POST" action="test.php">
<select id="multiselect" name="farming[]" multiple="multiple" required>
<option value="Irrigation">Irrigation</option>
<option value="Fertilizer">Fertilizer</option>
<option value="Pesticide">Pesticide</option>
</select>
<select id="multiselect" name="subject[]" multiple="multiple" required>
<option value="Irrigation">Technology</option>
<option value="Fertilizer">Science</option>
</select>
<div class="input-group">
<label>Marks</label>
<input type="number" name="marks">
</div>
<button type="submit" name="submit" class="btn">SUBMIT</button>
</form>
</body>
</html>`enter code here`
I expect to the Form to submit the selected data not just one to the database.
If you want to insert data in a single row
$subject = implode(',', $subjects);
this will return you single string with the separator ',' between every subject.
Now you can Insert this whole in a single column.
And then retrieve it use explode function with ',': it will give you the same array $subjects;
I have simplified it to this level but the only problem is that i am getting no data in the data base. What is likely the problem/
if <?php
$db = mysqli_connect('localhost','root','','trial') or die($db);
if (isset($_POST['submit'])) {
$marks = mysqli_real_escape_string($db,$_POST['marks']);
$subjects= $_POST['subject'];
$others= $_POST['others'];
foreach ($others as $t){
$sql1 = "INSERT INTO `trial_table` (`others`) VALUES ('".mysqli_real_escape_string($db,$t)."')";
mysqli_query($db,$sql1);
}
foreach ($subjects as $i){
$sql = "INSERT INTO `trial_table` (`subjects`, marks) VALUES ('".mysqli_real_escape_string($db,$i)."' , '$marks')";
mysqli_query($db,$sql);
}
}
?>
<body>
<form method="POST" action="test.php">
<select id="multiselect" name="subject[]" multiple="multiple">
<option value="Irrigation">Technology</option>
<option value="Fertilizer">Science</option>
</select>
<select id="multiselect" name="others[]" multiple="multiple">
<option value="Ball">Sports</option>
<option value="Netball">Gymics</option>
</select>
<div class="input-group">
<label>Marks</label>
<input type="number" name="marks">
</div>
<button type="submit" name="submit" class="btn">SUBMIT</button>
</form>
</body>
</html>
Below is the code where i created a drop down list, i am able to retrieve data from MySQL but i have to repeat the option step for every field, how can I setup a code for the drop down so i can just shorten to call it once in selection list, like in a for loop..also how do i create a error message to display if there is no selection, and if i select a data from the list it stores in the database
<form action="sign.php" method="post">
<label for="employee_name">Employee name</label>
<select name = "employee_name">
<option value=""> -----------Select----------- </option>
<?php
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
<label for="manager">manager</label>
<select name = "manager">
<option value=""> -----------Select----------- </option>
<?php
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
<label for="senior">Senior</label>
<select name = "Senior">
<option value=""> -----------Select----------- </option>
<?php
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
<input type="submit" name="register" value=" Click to Add"></button>
</form>
Use array and run query once to set options in array.
<?php
$optionArray = array();
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$optionArray[] = '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
?>
<form action="sign.php" method="post">
<label for="employee_name">Employee name</label>
<select name = "employee_name">
<option value=""> -----------Select----------- </option>
<?php
foreach($optionArray as $row)
{
echo $row;
}
?>
</select>
how can I setup a code for the drop down so i can just shorten to call it once in selection list, like in a for loop.
Just create a loop. though it should be foreach, not for.
First collect your data,
$people = $pdo->query('Select name from people order by name')->fetchAll(PDO::FETCH_COLUMN);
$sections = [
'employee_name' => 'Employee name',
'manager' => 'Manager',
'senior' => 'Senior',
];
and then loop it over
<form action="sign.php" method="post">
<?php foreach ($sections as $label => $caption): ?>
<label for="<?=$label?>"><?=$caption?></label>
<select name = "<?=$label?>">
<option value=""> -----------Select----------- </option>
<?php foreach ($people as $name): ?>
<option><?=$name?></option>
<?php endforeach ?>
</select>
<?php endforeach ?>
<input type="submit" name="register" value=" Click to Add"></button>
</form>
Instead of repeating this every time you can create a method which performs the same task.
<label for="employee_name">Employee name</label>
<select name = "employee_name">
<option value=""> -----------Select----------- </option>
<?=loadOptions('name','people');?> <!--shortcut way to echo in php-->
</select>
<?php
function loadOptions($field,$table){
$stmt = $pdo->prepare('Select '.$field.' from '.$table);
$stmt->execute();
$options='';
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$options .= '<option>'.$row['name'].'</option>';
}
return $options;
}
?>
I'm new to PHP and have created a very basic HTML form. As you can see in my form, the option values are all done by hand (there are more, I just simplified this example). What I want is for these to be generated dynamically using just PHP, so that I would physically have to add every single year etc.
I've done some searching but I can't seem to find exactly what I'm after so thought I'd ask here. From what I gather I need to create a query and echo out the option value somehow, although I'm not sure how to do this.
SELECT gameYear from games
I'd guess the above would be the correct query as all the form would need is the bookYear from the table?
<form id = "gameYear" method="get" action="result.php">
<label>
Game Year
<select name="gameYear">
<option value="2000">2000</option>
<option value="2001">2001</option>
<option value="2002">2002</option>
</select>
</label>
<input type = "submit" name="search" value = "Search">
</form>
Thanks, any help/guidance is appreciated.
<form id = "gameYear" method="get" action="result.php">
<label>
Game Year
<select name="gameYear">
<option value=''>--Select Year--</option>
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$SqlResult = mysqli_query($link, "SELECT gameYear from games");
while($Row = mysqli_fetch_array($SqlResult))
{
?>
<option value="<?php echo $Row['gameYear'] ?>"><?php echo $Row['gameYear'] ?></option>
}
?>
</select>
</label>
<input type = "submit" name="search" value = "Search">
</form>
<?php $sql = "SELECT gameYear from games order by gameYear ASC";
$result = mysql_query($sql, $connection) or die ("Couldn't perform query $sql <br />".mysql_error()); ?>
<form id="gameYear" method="get" action="result.php">
<label>Game Year
<select name="gameYear">
<?php while($row = mysql_fetch_array($result)){ ?>
<option value="<?php echo $row['gameYear'] ?>"><?php echo $row['gameYear']?></option>
<?php } ?>
</select>
</label>
<input type = "submit" name="search" value = "Search">
</form>
I wanted to select a table from a specific database and then the list of tables will appear in an option tag under select tag.
Thanks a lot.
Current Code:
<?php
include 'database/connectdatabase.php';
if(isset($_POST['select_db']))
{
$select_db = $_POST['select_db'];
$selectdb_query = 'SHOW TABLES FROM $select_db';
$query_select = mysql_query($selectdb_query,$connectDatabase);
if(!$query_select)
{
echo 'NO table selected!';
}
?>
<form method="POST" action="selecttable.php" autocomplete="off">
<select name="select_db">
<option selected="selected">Select Database</option>
<option>section_masterfile</option>
</select>
</form>
<form method="POST" action="#" autocomplete="off">
<?php while ($row = mysql_fetch_row($query_select)) {
$num_row = mysql_num_rows($row);?>
<select name="select_table">
<option selected="selected">Select Table</option>
<?php for($i=0;$i>=$num_row;i++){?>
<option><?php echo $row[0];?></option>
<?php}?>
</select>
<?php}?>
</form>
The problem is that you're already fetching rows yet you haven't even submitted the form yet.
I suggest restructure you logic this way:
$con = new mysqli('localhost', 'username', 'password', 'database');
$tables = array();
if(isset($_POST['select_db'])) { // if its submitted
$select_db = $con->real_escape_string($_POST['select_db']); // escape the string
$query = $con->query("SHOW TABLES FROM $select_db");
while($row = $query->fetch_assoc()) {
$tables[] = $row['Tables_in_' . $select_db]; // use associative instead
}
}
?>
<form method="POST" autocomplete="off">
<select name="select_db" onchange="this.form.submit();">
<option disabled selected>Select Database</option>
<option>test</option>
</select>
<br/><br/>
<select name="select_table">
<?php foreach($tables as $table): ?>
<option value="<?php echo $table; ?>"><?php echo $table; ?></option>
<?php endforeach; ?>
</select>
</form>
Sidenote: If you have turned on the error reporting, this should have given some red light to what you are doing wrong. Kindly turn it on.
error_reporting(E_ALL);
ini_set('display_errors', '1');
<select name="select_table">
<option selected="selected">Select Table</option>
<?php while ($row = mysql_fetch_row($query_select)) { ?>
<option value = "<?php echo $row[0]; ?>"><?php echo $row[0]; ?></option>
<?php } ?>
</select>
Try This
<form method="POST" action="#" autocomplete="off">
<select name="select_table">
<option selected="selected">Select Table</option>
<?php
while ($row = mysql_fetch_row($query_select))
{
?>
<option value="<?php echo $row[0];?>"><?php echo $row[0];?></option>
<?php
}
?>
</select>
</form>
Consider this code:
<form method="POST" action="#" autocomplete="off">
<select name="select_table">
<option selected="selected">Select Table</option>
<?php
while ($row = mysql_fetch_row($query_select)) {
?>
<option><?php echo $row[0];?></option>
<?php
}
?>
</select>
</form>
I am looking for a way to search for data from the database using input type box list, I tried make the code but it doesn't display anything:
html code:
<form action="users.php" method="post" name="searching">
<select name="users">
<option selected="selected" value="">-- select --</option>
<option value="1">user1</option>
<option value="2">user2</option>
<option value="3">user3</option>
</select>
<input type="submit" name="search" value="find">
</form>
php code:
if (isset($_POST['users'])) {
$key = trim ($_POST['users']);
$s = "SELECT * FROM users where user_name LIKE '%$key %'";
$res = mysql_query($s) or die('query did not work');
while($row = mysql_fetch_array( $res ))
{
?>
User ID: <?php echo $row['user_id'] ?>
User Name: <?php echo $row['user_name'] ?>
<?php
}
?>
when I try the code I didn't get any result and when I remove the while loop and put this instead of it :
<?php echo $key; ?>
it gives me the numbers of the selected value, for example if I select user2 the result will be 2. and I want the result to be user id and user name.
you need to fetch all the user name in your drop down select box
<select name="users">
<option selected="selected" value="">-- select --</option>
<?php $s2 = "SELECT * FROM users";
$q2=mysql_query($s2) or die($s2);
while($rw=mysql_fetch_array($q2))
{
echo '<option value="'.$rw['userid'].'">'.$rw['username'].'</option>';
}</select>
?>
<?php if (isset($_POST['search'])) { // submit button name here
$key = $_POST['users'];
$s = "SELECT * FROM users where user_id='".$key."'";
$res = mysql_query($s) or die($s);
while($row = mysql_fetch_array( $res ))
{
?>
User ID: <?php echo $row['user_id'] ?>
User Name: <?php echo $row['user_name'] ?>
<?php
}
?>
edit your html to this,you will get the in $_POST which will be in value='something'
<form action="users.php" method="post" name="searching">
<select name="users">
<option selected="selected" value="">-- select --</option>
<option value="user1">user1</option>
<option value="user2">user2</option>
<option value="user3">user3</option>
</select>
<input type="submit" name="search" value="find">
</form>
Or if value is the id of user then change query to this
$s = "SELECT * FROM users where user_id='".$key."'";