2 Forms (select) - 1 is dependent from 2 - php

I want create form in html+php. I have got 2 tables in my database.
Categories: id_category, category
Dairy: id_dairy, id_category, product_name
And now is question. How can I create 1 form with 2 select dropdowns. Is it possible to do it in PHP without AJAX?
I mean that - I want choose Category and then choose Products without refresh page.
Code:
<form role="form" action="kalorie.php" method="post">
<div class="form-group">
<label for="kategoria">Kategoria:</label>
<select class="form-control" name="kategoria">
<option>Wybierz kategorie</option>
<?php
$sql_1 = "SELECT * FROM produkty";
$result_1 = mysqli_query($conn, $sql_1);
while($row_1 = mysqli_fetch_assoc($result_1)) {
echo '<option>'.$row_1["produkt"].'</option>';
}
$kat = $_POST['kategoria'];
?>
</select>
<select class="form-control" name="produkt">
<option>Wybierz produkt</option>
<?php
$sql_2 = "SELECT * FROM $kat";
$result_2 = mysqli_query($conn, $sql_2);
while($row_2 = mysqli_fetch_assoc($result_2)) {
echo '<option>'.$row_2["produkty"].'</option>';
}
?>
</select>
</div>
<button type="submit" class="btn btn-default" name="oblicz">Wyślij</button>
</form>

Ajax is best solution for this.
But if you want an alternative than you can use "iframe" and submit ypur form in that frame.

Non Ajax solution:
Load your product subcategories into a JavaScript object keyed by the category id. When the category is changed in the category select list, swap out the options in the product list.
<script>
var produkts = {
<?php
$sql_2 = "SELECT * FROM $kat";
$result_2 = mysqli_query($conn, $sql_2);
$id_category = 0;
list($delim1, $delim2) = array('', '');
while($row_2 = mysqli_fetch_assoc($result_2)) {
$delim2 = '"';
$row_2 = $row['value'];
if ( $id_category != $row_2['id_category'] ) {
$id_category = $row_2['id_category'];
echo $delim1 . $id_category . ': "';
$delim1 = '", ';
}
echo '<option>' . $row_2['produkty'] . '</option>';
}
echo $delim2;
?>
};
// example: {1: "<option>cheese</option><option>butter</option>", 2: "<option>ice cream</option>"}
</script>
<form role="form" action="kalorie.php" method="post">
<div class="form-group">
<label for="kategoria">Kategoria:</label>
<select class="form-control" name="kategoria">
<option>Wybierz kategorie</option>
<option value="1">Me</option>
<option value="2">You</option>
<?php
$sql_1 = "SELECT * FROM produkty";
$result_1 = mysqli_query($conn, $sql_1);
while($row_1 = mysqli_fetch_assoc($result_1)) {
echo '<option>'.$row_1["produkt"].'</option>';
}
$kat = $_POST['kategoria'];
?>
</select>
<select class="form-control" name="produkt">
<option>Wybierz produkt</option>
</select>
</div>
<button type="submit" class="btn btn-default" name="oblicz">Wyślij</button>
</form>
<script>
document.querySelector('select[name=kategoria]').addEventListener('change', function (evt) {
var kat = evt.target;
var kat_sel = kat.options[kat.selectedIndex].value
document.querySelector('select[name=produkt]').innerHTML = produkts[kat_sel];
})
</script>
Mocked up JSFiddle demo.

Related

My PHP Code is Not Updating Values In Database

I have tried to write a code that update category in the database using admin panel but whenever i try to do that it won't work and i don't get any errors to look into it, please help guys; thanks a lot
PHP Code:
<?php
if (isset($_GET['edit'])) {
$edit_id = $_GET['edit'];
$query = "SELECT * FROM categories WHERE category_id = $edit_id ";
$edit_get_result = mysqli_query($connection,$query);
if (!$edit_get_result) {
die("Edit Get Result Query FAILED");
}
while ($category_name_row=mysqli_fetch_assoc($edit_get_result)) {
$category_name = $category_name_row['category_name'];
}
?>
<center>
<form action="category.php" method="POST">
<div class="form-group">
<label for="update_category">Update Category</label>
<input type="text" class="form-control" id="update_category" value="<?php if(isset($category_name)){echo $category_name; } ?>" name="update_category" aria-describedby="emailHelp" placeholder="Enter Category Name">
</div>
<button type="submit" name="update_category_submit" class="btn btn-primary">Update</button>
</form>
</center>
<?php
if (isset($_POST['update_category_submit'])) {
$category_name = $_POST['update_category'];
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$final_update_query_result = mysqli_query($connection,$query);
if (!$final_update_query_result) {
die("Final Update Query Result FAILED");
}
}
}
?>
Please check below code. You need to pass edit_id in your form POST. I have put it in a hidden input and set it's value according to the GET parameter from top of your php part.
<?php
if (isset($_GET['edit'])) {
$edit_id = mysqli_real_escape_string($connection,$_GET['edit']);
$query = "SELECT * FROM categories WHERE category_id = '$edit_id' ";
$result = mysqli_query($connection,$query);
if(!$result) {
die("Edit Get Result Query FAILED");
}
while ($row=mysqli_fetch_assoc($result)) {
$category_name = $row['category_name'];
}
?>
<center>
<form action="category.php" method="POST">
<div class="form-group">
<label for="update_category">Update Category</label>
<input type="text" class="form-control" id="update_category" value="<?php if(isset($category_name)){echo $category_name; } ?>" name="update_category" aria-describedby="emailHelp" placeholder="Enter Category Name">
</div>
<input type="hidden" name="edit_id" value="<?php if(isset($edit_id)) echo $edit_id;?>">
<button type="submit" name="update_category_submit" class="btn btn-primary">Update</button>
</form>
</center>
<?php
if (isset($_POST['update_category_submit']) && isset($_POST['edit_id'])) {
$category_name = mysqli_real_escape_string($connection,$_POST['update_category']);
$edit_id = mysqli_real_escape_string($connection,$_POST['edit_id']);
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$result = mysqli_query($connection,$query);
if (!$result) {
die("Final Update Query Result FAILED");
}
else echo "Final Update Query Result Success";
}
?>
Hi have noticed that you have used raw inputs. try avoiding it. Also noticed your code had extra curly braces at the end.
Please try using the following code after replacing your end page section php script.
if (isset($_POST['update_category_submit'])) {
$category_name = $_POST['update_category'];
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$final_update_query_result = mysqli_query($connection,$query);
if (!$final_update_query_result) {
die("Final Update Query Result FAILED");
}
}
And Change your query variable to the following:
$query = "SELECT * FROM categories WHERE category_id = ".$edit_id;

Populating Second Dropdown Based on first dropdown from the database table without using javascript

I am trying to create a form for the admin of an e-commerce site and the admin should be able to create a category and add new products.
I have two tables in my database from where I want to populate the dropdown list. I want the second dropdown to populate as I select the first drop-down value but I have to do it without the submit button.
This is the code for the form with two drop-downs:-
<form method="post" action="add_category.php">
<h4>Choose the root level:</h4>
<select name="rootLevel">
<?php
$conn = mysqli_connect("localhost","root","","store")
or die("Error in Connection on add_category");
$query = "SELECT * FROM root_category";
$result = mysqli_query($conn,$query) or die("Query failed add_category");
$id=1;
//echo $id;
//echo "Hello";
while($row = mysqli_fetch_assoc($result)){
global $id;
//echo "<h1>$id</h1>";
$id = $row['id'];
echo "<option name='rootLevel' value=$id>".$row['Name']."</option>";
//echo "<option>$id</option>";
}
?>
</select>
<br><br>
<h4>Choose the Level 1 Category:</h4>
<select name="level1">
<?php
global $id;
//echo "<option>".$_POST['rootLevel']."</option>";
$query_level1 = "Select * from level1_category Where P_id = $id";
$result1 = mysqli_query($conn,$query_level1) or die("Query failed level 1");
while($row = mysqli_fetch_assoc($result1)){
$id1 = $row['P_id'];
echo "<option name='level1' value=$id1>".$row['Name']."</option>";
}
?>
</select>
I have successfully populated the first drop-down and now I want to fetch the $id in 'resultValue' without the submit button.
You cant do this only with PHP. You have to use jquery OR Ajax to do this.
Please check this example page . This may help you
https://www.tutorialrepublic.com/faq/populate-state-dropdown-based-on-selection-in-country-dropdown-using-jquery.php
OR
https://www.codexworld.com/dynamic-dependent-select-box-using-jquery-ajax-php/
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "states.php",
data: { country : selectedCountry }
}).done(function(data){
$("#states").html(data);
});
});
});
</script>
</head>
<body>
<div class="form-group">
<label for="country" class="input__label">Country</label>
<select id="country" onchange="states(this.value);" name="country" class="country form-control login_text_field_bg input-style">
<option selected>Choose...</option>
<?php
$sql= $cnn->prepare("SELECT key_iso_code FROM country");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
?>
<option><?php echo $key_iso_code ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState" class="input__label">State/Province</label>
<select id="states" name="state" class="form-control input-style">
<option selected>Choose...</option>
</select>
</div>
</body>
<?php
include("PDOConnection.php");
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];
// Display city dropdown based on country name
if($country !== 'Shoose...'){
$sql= $cnn->prepare("SELECT state.key_name FROM country INNER JOIN state ON country.key_id = state.key_country_id WHERE country.key_iso_code like '$country'");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
echo "<option>". $key_name . "</option>";
}
}
}
?>

Updating with multiple select <option selected="selected">

I have a form where a user can update several data inside the database and one of the fields is using a multiple select. I'm stuck with the selected part, where the system will display back the keyword values from the database in the option. The updating process works fine, the problem is only to display the existing values from the database inside the multiple select options.
<form action="" method="post" enctype="multipart/form-data">
<?php
if(isset($_GET['edit'])) {
$id = $_GET['edit'];
$query = "SELECT * FROM record WHERE id = $id";
$select_id = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($select_id)){
$keywords = explode (', ', $row['record_keywords']) ;
?>
<label class="control-label">Keywords</label>
<select multiple name="keywords[]" type="next" class="selectpicker" data-style="btn btn-default btn-block">
<?php
$query = "SELECT * FROM key";
$select_categories = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($select_categories)) {
$kk = $row['key'] == $keywords;
echo '<option '.($kk ? 'selected="selected"' : '').'>' . $row['key'] . '</option>';
} ?>
</select>
<button class="btn btn-warning btn-fill btn-wd btn-finish pull-right" name="update" type="submit">Update</button>
<?php
}//end of while
}//end of if
?>
</form>

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>

View customer info on select change

I'm creating a page which will allow an admin to select a user from a drop down list, which populates from a database. When the person is selected, the info associated with that person will then be viewed on the page. I already have a select statement which selects all the info and the drop down menu is populating correctly. However, I'm unsure on how to get that selected user's info to display on the page once selected. Would I need to do an entirely different select statement and query which checks which customer was selected? Or is there another way?
customer.php
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name='selectCust' id='selectCust'>";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
echo "<option>$name</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
viewUser.php
if(isset($search)){
$select = "SELECT * FROM $cust WHERE acctNum='{$search}'";
$result = mysqli_query($db, $select);
if(mysqli_num_rows($result) > 0){
if($row = mysqli_fetch_assoc($result)){
$acct = "{$row['acctNum']}";
echo $acct;
}
}
}
script.js
$(document).ready(function(){
function searchAjax(){
var search = $('#selectCust').val();
$.post('includes/viewUser.php', {searchUsers: search}, function(data){
$('#view_form').append(data);
})
}
$('#selectCust').on('change', function(ev){
ev.preventDefault();
searchAjax();
})
})
Search.php
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$(".dropdown-users").on("change",function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
var search_this=$("dropdown-users").val();
$.post("Ajaxsearch.php", {searchusers : search_this}, function(data){
$(".results").html(data);
})
}
</script>
<div id="view_form" class="view">
<form method="post">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select class="dropdown-users">";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo "<option value="$acct">$name ($acct)</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="<span id="IL_AD1" class="IL_AD">submit</span>" <span id="IL_AD6" class="IL_AD">value</span>="Search" id="button_find" />
<div class="results"></div>
//********************************************************************************************
********************************************************************************************//
Ajaxsearch.php
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db"); // Enter your information here
$term = $_POST['searchusers']
$term = mysqli_real_escape_string($con, $term);
if($term == "")
echo "Enter Something to search";
else {
$query = mysqli_query($con, "select * from USERDATEBASEHERE where ID = '{$term}' ");
$string = '';
if (mysqli_num_rows($query) > 0) {
if (($row = mysqli_fetch_assoc($query)) !== false) {
$string = "{$row['ID']}";
}
} else {
$string = "This Person does not exist";
}
echo $string;
}
?>
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name=\"somename\" onchange=\"this.form.submit();\">";
echo "<option value=\"\">Select User</option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo '<option value="'.$acct.'">$name ($acct)</option>';
}
echo "</select>";
?>
</fieldset>
</form>
</div>
The options must have some refering value, through which you can retrieve the details of selected user, whenever the value of option is not initiated then the default value of the option will be option's label.

Categories