Using Select Option's value to query database [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have the following code to generate my option:
<?php
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $rows) {
$id = $rows[MyID];
$option.="<option>".$id."</option>";
}
?>
<select name="options" id="options" class="options">
<option value="$id">Select an Option</option>
<?php echo $option?>
</select>
I would like to use the value of the selected option in my next query.. like this:
<?php
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
This is not working for some reason. Can you please help on this. Thanks

<?php
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
$result = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$id = $row['MyID'];
$option.='<option value="'.$id.'">'.$id.'</option>';
}
?>
<form method="post" action"(`The url of the next page`)">
<select name="options" id="options" class="options">
<option disabled>Select an Option</option>
<?php echo $option?>
</select>
<input type="submit" value="submit" />
</form>
Next page:
<?php
if(isset($_POST['submit']) && isset($_POST['options'])) {
$option = $_POST['option'];
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
}
With fetchAll() you should assign this to a variable and then loop through that.
$row[MyID] MyID should be wrapped in '' or "" as the index is a string so $row['MyId']
You'll need to submit the data back to the server for PHP to be able to do anything with it as PHP creates he HTML and then sends it from the server to the browser.
I've used if(isset()) for the REQUEST variables ($_GET, $_POST), this will prevent PHP from throwing errors if you try and load the page without them being available.
If you have any other questions, I'd be happy to help.
Hope this helps! :)
EDIT
<?php
if(isset($_GET['submit']) && isset($_GET['options'])) {
$option = $_GET['option'];
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
/**
* You'll need to put the logic for the query above here
**/
} else {
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
$result = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$id = $row['MyID'];
$option.='<option value="'.$id.'">'.$id.'</option>';
}
?>
<form method="get" action"">
<select name="options" id="options" class="options">
<option disabled>Select an Option</option>
<?php echo $option?>
</select>
<input type="submit" value="submit" />
</form>
<?php
} // End of else
?>
I've also changed the form method to get and removed the action, so it will submit to the current page.

Related

How to populate dropdown field pre-selected with the existing data from another MySQL table?

In my database I have 2 tables:
To insert data, I have a form that populates dropdown options from the table formulation. This is what the insert form for formulation dropdown looks like:
<?php
$formulation = '';
$query = "SELECT * FROM formulation";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
$formulation .= '<option value="' . $row["formulationID"] . '">' . $row["formulation_name"] . '</option>';
}
?>
<select>
<option value="">Select formulation</option>
<?php echo $formulation; ?>
</select>
Now I am working on the ‘Update’ form. But my question is how can I populate the ‘Formulation’ field dropdown with the data from the formulation table (like as the insert form) but pre-selected with the existing formulation value for the name from the items table? Like this image below:
I am having problem with how I should build the form. How should I proceed with this form?
<?php
$output = array('data' => array());
$sql = "SELECT * FROM items";
$query = $connect->query($sql);
while ($row = $query->fetch_assoc()) {
$output['data'][] = array(
$row['name'],
);
}
echo json_encode($output);
?>
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text"><br>
<label>Formulation</label>
<select >
<!--What should be the codes here? -->
</select>
</div>
<button type = "submit">Save changes</button>
</form>
Thanks in advance for your suggestion.
Note: I'm not a user of mysqli so maybe there will be some error, but you will get the idea. This will not tackle the update part, just the populate part
Since you are editing a certain item, I will assume that you have something to get the item's itemID.
<?php
$sql = "SELECT * FROM items WHERE itemID = ?";
$query = $connect->prepare($sql);
$query->bind_param("s", $yourItemID);
$query->execute();
$result = $query->fetch_assoc();
$itemName = $result['name'];
$itemFormulation = $result['formulation_fk'];
//now you have the name and the formulation of that certain item
?>
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text" value="<?php echo $itemName; ?>"><br>
<label>Formulation</label>
<select >
<?php
$query = "SELECT * FROM formulation";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['formulationID']; ?>" <?php echo ($row['formulationID'] == $itemFormulation) ? 'selected' : ''; ?>>
<?php echo $row['formulation_name']; ?>
</option>
<?php
}
?>
</select>
</div>
<button type = "submit">Save changes</button>
</form>
I changed the code to better suit the problem, there may be typos, just comment for clarification
If I have understand Your question... You have to put Your result into a string. For example:
<?php
$output = array('data' => array());
$sql = "SELECT * FROM items";
$query = $connect->query($sql);
$option = '';
while ($row = $query->fetch_assoc()) {
$name=$row['name'],
$option.='<option value="$name">$name</option>'
}
echo json_encode($output);
?>
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text"><br>
<label>Formulation</label>
<select >
<?=$option?>
</select>
</div>
<button type = "submit">Save changes</button>
</form>
I hope to be of help
This should do the trick:
<?php
$itemsSql = "SELECT * FROM items WHERE itemId = 5";
$itemQuery = $connect->query($sql);
$item = $itemQuery->fetch_assoc();
$formulationsSql = "SELECT * FROM formulation";
$formulationsQuery = $connect->query($sql);
$formulations = $itemQuery->fetch_assoc();
?>
<form action="updateItem" method="POST">
<div>
<label>Item Name</label>
<input type="text" value="<?= $item[0]['name']; ?>"><br>
<label>Formulation</label>
<select>
<?php foreach($formulations as $formulation){
echo '<option value="'. $formulation['formulationId'].'">' .
$formulation['formulation_name'] . '</option>';
} ?>
</select>
</div>
<button type = "submit">Save changes</button>
</form>

Get value from MySQL database and populate dropdown box [duplicate]

This question already has answers here:
Using PHP to populate a <select></select> dropdown? [duplicate]
(7 answers)
Closed 7 months ago.
I hope someone can help me figure this out as I'm new to PHP and MySQL. But basically, what I'm trying to do is to pull the data from the database and populate the dropdown box and textbox, and so I can update the value in the textbox.
This is the table structure:
id | hf_name | hf_price
------------------------
AI | test 1 | 123
AI | test 2 | 123
So let's say I wanna update "test 1" price, I would select "test 1" in the dropdown selection and update the price in the textbook.
This are my code:
<form class='data_form' action='data/food_update.inc.php' method='post'>
<select>
<?php while ($row = mysqli_fetch_array($result)):; ?>
<option><?php echo $row[1];?></option>
<?php endwhile;?>
</select>
<input type='number' name='hf_price' placeholder='$'>
<button type='submit'>UPDATE</button>
</form>
Include:
<?php
//CONNECTION TO MySQL
include '../dbh.php';
//VARIABLES
$hf_name = $_POST['hf_name'];
$hf_price = $_POST['hf_price'];
$by_user = $_SESSION['Fname'];
$up_date = date('Y-m-d');
$sql = "SELECT hf_name FROM hotfoods";
$result = mysql_query($conn, $sql);
?>
Thanks!
Try changing the option to
<option value="<?php echo $row[2];?>"><?php echo $row[1];?></option>
Where I'm assuming $row[2] variable contains the hf_price value.
$query = "select * from tablename";
$result = mysqli_query($query);
<select>
<?php
while($row = mysqli_fetch_assoc($result){
?>
<option value='<?php echo $row['hf_name']; ?>'><?php echo $row['hf_name']; ?></option>
<?php
}
?>
</select>
but for this you need to change your id datatype into int,
$query = "select * from tablename";
$result = mysqli_query();
<select id="nameID" name="hf_name">
<?php
while($row = mysqli_fetch_assoc($result){
?>
<option value='<?php echo $row['id']; ?>'><?php echo $row['hf_name']; ?></option>
<?php
}
?>
</select>
This will be fine when you fetch details but it does not update any value because for this you need to use Ajax or Jquery for update on Select, let me to try it.
Ajax
$("#nameID").onchange(function(){
var id = $("#id").val();
$.ajax(
url: "update.php",
type: "POST",
data: {'id'=id},
success: function(){
alert("ok");
});
});
Try this it might work.
You should assign a name attribute value (in this case, hf_name) on select element so that that become available in $_POST array.
<form class='data_form' action='data/food_update.inc.php' method='post'>
<select name="hf_name">
<?php while ($row = mysqli_fetch_array($result)):; ?>
<option value="<?php echo $row['hf_name']?>"><?php echo $row['hf_name'];?></option>
<?php endwhile;?>
</select>
<input type='number' name='hf_price' placeholder='$'>
<button type='submit'>UPDATE</button>
</form>
Now this is on which the form will be submitted. Where you can take user's submitted data through $_POST array.
<?php
//CONNECTION TO MySQL
include '../dbh.php';
//VARIABLES
$hf_name = $_POST['hf_name'];
$hf_price = $_POST['hf_price'];
$query = sprintf("UPDATE hotfoods SET hf_price='%d' WHERE hf_name='%s'",
mysql_real_escape_string($hf_price),
mysql_real_escape_string($hf_name));
$result = mysql_query($conn, $query);
if ($result) {
echo 'Price updated!';
} else {
echo 'Problem while updating price';
}
?>

PHP mySQL select via html select

I'm trying to do a select from a table based on the post value of an HTML select box. I'm getting no results at all, I'm echoing out the post value no problem. The statement works on it's own but won't when I use the select form to populate it. This is just my test I will be adding other options to the dropdown box.
<?php
if(isset($_POST['value'])) {
if($_POST['value'] == 'Militaria') {
$query = "SELECT * FROM listings WHERE category1=Militaria";
}
else {
// query to get all records
$query = "SELECT * FROM listings";
}
}
$sql = mysql_query($query);
while ($row = mysql_fetch_array($query)){
echo 'Description:' . $row['description'];
}
mysql_close($con);
?>
Here is the html form I'm using, can anyone tell me where I'm going wrong, should I do it a different way etc, I'm new to php? Thanks!!
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='form_filter' >
<select name="value">
<option value="all">All</option>
<option value="Militaria">Militaria</option>
</select>
<br />
<input type='submit' value = 'Filter'>
</form>
mysql_fetch_array() should receive resorce as a parameter. Try mysql_fetch_array($sql).
Quote around 'Militaria' and mysql_fetch_array($sql)
<?php
if(isset($_POST['value'])) {
if($_POST['value'] == 'Militaria') {
$query = "SELECT * FROM listings WHERE category1='Militaria'";
}
else {
// query to get all records
$query = "SELECT * FROM listings";
}
$sql = mysql_query($sql);
while ($row = mysql_fetch_array($sql)){
echo 'Description:' . $row['description'];
}
mysql_close($con);
}
?>
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='form_filter' >
<select name="value">
<option value="all">All</option>
<option value="Militaria">Militaria</option>
</select>
<br />
<input type='submit' value = 'Filter'>
</form>
You have two mistakes in your php code.
1st : quote around Militaria. The query should be, $query = "SELECT * FROM listings WHERE category1='Militaria'";
2nd : mysql_fetch_array accepts executed query's result as parameter. It should be, $row = mysql_fetch_array($sql)
Final code:
<?php
if(isset($_POST['value'])) {
if($_POST['value'] == 'Militaria') {
$query = "SELECT * FROM listings WHERE category1 = 'Militaria'";
}
else {
// query to get all records
$query = "SELECT * FROM listings";
}
}
$sql = mysql_query($query);
while ($row = mysql_fetch_array($sql)){
echo 'Description:' . $row['description'];
}
mysql_close($con);
?>

fill other text inputs with MySQL values based on select box option

I have this select box that populates from MySQL Data using PHP
<select>
<?php
$stmt = $pdo_conn->prepare("SELECT * from prices ");
$stmt->execute(array());
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($records as $result2) {
echo '<option value="'.$result2["product"].'">'.$result2["product"].'</option>';
}
?>
</select>
in the same table in MySQL (prices) there is a retail column, how can i put the value of retail into a text input
<input type="text" name="unitprice" />
based on the selected row in the select box?
I'd recommend using JavaScript.
Option 1
I would convert your results into a JSON Array and echo it to JavaScript. This way all information gets given the user.
<select id="mySelectBox" onchange="changeValue(this.value);">
<?php
$json_array = array();
$stmt = $pdo_conn->prepare("SELECT * from prices ");
$stmt->execute(array());
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($records as $result2) {
$product = $result2["product"];
$json_array[$product] = $result2['unitprice'];
echo '<option value="'.$result2["product"].'">'.$result2["product"].'</option>';
}
json_encode($json_array, JSON_FORCE_OBJECT);
?>
</select>
<input type="text" id="unitPrice" name="unitprice" />
<script>
var json = <?php echo $json_array; ?>;
function changeValue(myValue) {
document.getElementById("unitPrice").value = json[myValue];
}
</script>

Populating dropdown with sql results

I have the following code to display a dropdown based on the sql query but nothing is displaying when i run the code.
<?php
require ("common.php");
$sql = "SELECT FullName FROM Users";
$query = $db->prepare($sql);
$query->execute();
$option = "";
while($rows = $query->fetchAll(PDO::FETCH_ASSOC)) {
$name = $rows["FullName"];
$option.="<option>".$name."</option>";
}
?>
<div class="aClass">
<p class="select">Name</p>
<select name="aName" id="aName">
<option value="0">Select UserName</option>
<?php echo $option?>
</select>
</div>
$option you added an s
<?php echo $option;?>
Replace while with
foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $rows) {
...
}
while($rows = $query->fetchAll(PDO::FETCH_ASSOC)) will return the entire set of results which will not evaluate to true,leaving $name undefined,you want to iterate over the results.

Categories