Add Item Drop Down List - php

I have a drop down list which i filled with items from my database "mydatabase".
connect.php
<?php
$dbname = 'mydatabase';
$dbuser = 'louie';
$dbpass = '';
?>
mydatabase contains the table 'Users' with 'Name' and 'NameID' column.
index.php
<?php
include ("connect.php");
$mysqli = new mysqli("localhost", $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<div class="label">Select Name:</div>
<select name="names" onchange="change(this.value)">
<option value = "none">---Select---</option>
<?php
$query = "SELECT `Name` FROM `Users`";
$mysqli = mysqli_query($mysqli, $query);
while ($d=mysqli_fetch_assoc($mysqli)) {
echo "<option value='{".$d['Name']."}'>".$d['Name']."</option>";
}
?>
</select>
<select name="nid" id="nameid">
</select>
In my name column there is two values. Louie and Jane which fills the first dropdown "names". What I want to do is whenever I select the Louie, the second drop down with the id 'nameid' will be filled with the NameID column from my database.
I've got some idea in disabling the second drop down but without the database.
<script>
function change(value) {
if(value=="none")
document.getElementById("nameid").disabled=true;
else
document.getElementById("nameid").disabled=false;
}
</script>
But I don't know how to fill the second dropdown with NameID column by selecting the Louie in first drop down.

try something like this:
var x = document.createElement("OPTION");
x.text = value;
var s = document.getElementById("nameid");
s.add(x);

The trick here is to understand that only PHP can access your database, and that reacting on UI changes is a javascript issue. That means that if you want the nameID on your second dropdown, php first needs to already provide it somewhere, and next you'll need some javascript to actually show it.
This is a possible solution:
<!-- note I changed the function onchange="change(this.value)" to onchange="change(this)"
because this.value is actually not the value.. -->
<select name="names" onchange="change(this)">
<option value = "none">---Select---</option>
<?php
// Select both columns you want to use in PHP
$query = "SELECT `NameID`, `Name` FROM `Users`";
$mysqli = mysqli_query($mysqli, $query);
// I used the value field to hold the id, rather than the name, while the name is shown to the user.
while ($d=mysqli_fetch_assoc($mysqli)) {
echo "<option value='".$d['NameID']."'>".$d['Name']."</option>";
}
// your other code...
?>
<script>
function change(oSelect) {
var value = oSelect.options[oSelect.selectedIndex].value;
var name = oSelect.options[oSelect.selectedIndex].innerHTML;
if(name=="Louie") {
document.getElementById('nameid').innerHTML = "";
for (var i=0; i<oSelect.options; i++) {
document.getElementById('nameid').innerHTML += "<option value='"+oSelect.options[i].value+"'>"+oSelect.options[i].value+"</option>";
}
}
}
</script>

Related

How to pass the dropdown list selected value from a php form to a mysql query

The function of this web application is to: select a customer from the dropdown list (the dropdown list values are auto popup from the database), it will print the selected customer name and its postcode on the result page.
When I choose the customer name from the dropdown list and click the submit button, the result page only prints the $customerv value (the 1st echo), but the $result value (2nd echo) was not printed. The customer name is unique in the database.
index.php:
<?php
require_once('config.php');
?>
<!DOCTYPE HTML>
<html>
<form action="result.php" method="post">
Customer:<br>
<select Customer id="customer" name="Customer">
<option value="">--- Select Customer ---</option>
<?php
$sql = "SELECT b.BPName from BP b where b.BPCode like 'C%' Order by b.BPName";
$customer = mysqli_query($conn, $sql);
while ($cat = mysqli_fetch_array(
$customer,
MYSQLI_ASSOC
)) :;
?>
<option value="<?php echo $cat['BPName']; ?>">
<?php echo $cat['BPName']; ?>
</option>
<?php
endwhile;
?>
</select>
<input type="submit" value="Submit">
</form>
</html>
config.php:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$databse = "xxx";
$conn = new mysqli($servername, $username, $password, $databse);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
result.php:
<table>
<?php
require_once('config.php');
$customerv = $_POST['Customer'];
echo $customerv;
$sql = "SELECT shiptozipcode FROM BP WHERE BPName ='$customerv'";
$result = $conn->query($sql);
echo $result;
?>
</table>
The query result itself isn't something that's "printable" to the page. It's not just a single value, it's a complex object. You need to fetch the record(s) from the result. For example:
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row["shiptozipcode"];
}
If you're sure there will be only one row (it's still a good idea to add some error checking anyway) then you don't need the loop:
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row["shiptozipcode"];
But either way, you need to extract the data from the result set. (You could also use fetch_object() instead of fetch_assoc() if you prefer object syntax over array syntax.)
As an aside, be aware that your query is wide open to SQL injection. Now would be a good time to learn how to correct that.

get dropdown data on another dropdown change

I have a drop down menu having column names same as they are in database table. I have inserted every column name in option tag of dropdown menu. These columns have number of rows in database.
After that, I have another drop down menu. I want to show all the data rows of the selected column in the previous drop down menu.
E.g. I have column names as a,b,c,d in the first drop down and every column has data in database table. So, If I select A in first drop down; It shows all the data rows of A in next drop down. Here is the code:
<select name="first">
<option selected="true" disabled="disabled">Select an Option</option>
<option value="select_all">Select All</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">c</option>
</select>
<?php
if(isset($_POST['first'])){
$first=$_POST['first'];
}
?>
<select name="firstres" id="firstres"><option style="display:none;" selected; value="">---Select an option---</option><?php
#mysql_connect('localhost', 'root', '');
#mysql_select_db('db');
$first=$_POST['first'];
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db' AND TABLE_NAME = 'tbl' AND COLUMN_NAME LIKE '" . $_POST["first"] . "'";
$result = #mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value=' " . $row['first'] ."'>" . $row['first'] ."</option>";
}
?>
</select>
The problem is; I am not getting column rows in second drop down menu.
You need to use Ajax for this issue, here my code maybe you can use on your projects.
View Code
<select id="category">
<option value="1">Category</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
<select id="sub_category">
<option>Chose Category</option>
</select>
Ajax Code
$(document).ready(function(){
$('#category').on('change',function(){
var category_id = $(this).val();
if(category_id){
$.ajax({
type:'POST',
url:'sub_category.php',
data: {
category_id : category_id
},
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option>Pilih Sub category Kelas</option>');
}
});
});
sub_category.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$category_id = $_POST['category_id'];
$sql = "SELECT id,sub_category FROM category where category_id = $category_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value='".$row["id"]."'>".$row["sub_category"]."</option>";
}
} else {
echo "<option>Empty Sub Category</option>";
}
$conn->close();
?>
First of all, I do recommend to stay in php for the whole code.
-> Make things easier for the future...
Example:
$output = <<< EOD
<option>Select an Option</option>
etc.
EOD;
echo $output;
Second, did you run through the code step by step?
what is the output for $first and $_POST['first']; ?
Are they correct?
Is the SQL statement correct?
Table and column names....
Third, I understand, that you want select from the first dropdown and than the output from the database should appear.
This won't work in that way. HTML is stateless. This means everything which has been send to client is no longer available for the server.
So you need to use some code to resend this information: For example JSON (AJAX) or via HTML (which is not so nice). Look here:
https://www.w3schools.com/js/js_ajax_intro.asp

PHP - SAVE select option value AFTER submission

I have a drop down menu which lists the associated 'IDs' from the mysql database:
<fieldset>
<legend><strong>Change ID:</strong></legend>
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "change_management";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$query3 = "SELECT `change_id` FROM `change_request_tbl` WHERE (approval_disposition LIKE 'Requires Editing')";
$result3 = mysqli_query($connect,$query3);
?>
<select required name="change_id">
<option value="">Please specify...
<?php
while ($roww = mysqli_fetch_array($result3))
{
echo "<option value='".$roww['change_id']."'>".$roww['change_id']."</option>";
}
?>
</select>
<input type="submit" name="get" value="Get Details" class="btn">
</fieldset><br><br><br>
When the user clicks "Get Details" the dropdown reverts back to "Please specify". I have found many examples of how to save the value after submission, but none seem to be applicable to my code as I am fetching values from the database.
Is there anyway to save the last inputted values in this current format?
When the user submits the form, the form value change_id has the value you're looking for. So when populating your option elements you can check if any of them match what was submitted and set it to be selected. Something like this:
if (isset($_POST['change_id']) && $roww['change_id'] == $_POST['change_id']) {
echo "<option selected value='".$roww['change_id']."'>".$roww['change_id']."</option>";
} else {
echo "<option value='".$roww['change_id']."'>".$roww['change_id']."</option>";
}
Or if you want it all on one line (using the ternary conditional operator):
echo "<option ".((isset($_POST['change_id']) && $roww['change_id'] == $_POST['change_id']) ? "selected" : "")." value='".$roww['change_id']."'>".$roww['change_id']."</option>";

Extracting 2 values from different columns from a DB with only 1 Select

Problem solved: This is the solution, thanks to #dont-panic and everyone who helped me !
while($row = mysql_fetch_assoc($get)) {
$option .= '<option id="opcion" value="'.$row['nombre'].'">'
.$row['nombre']
.'</option>';
if (isset($_POST['postre']) && $row['nombre'] == $_POST['postre']) {
$preciodelpostre = $row['precio'];
}
} ?>
as the title say, I'm trying to make a very simple accounting website for my grocery store where I keep my daily sales registered. I already made a form to add new articles in the Database with these table names:
Table: Postres -- postreID(id of the article), nombre(name of the
article), price(price of the article).
I also have another table called "ventas", which is where I wanna store all my sales based on a date criteria, which is already done.
Table: Ventas -- id(sale id), fecha(date of registered sale),
postre_vendido(name of the article sold), ganancia(the article price).
This is my code to register my sales:
<?php
$dbhost = 'db641973975.db.alansete.com';
$dbuser = 'dbo675';
$dbpass = 'dotCos215';
$dbname = 'db643975';
$con = mysql_connect($dbhost,$dbuser,$dbpass);
$db = mysql_select_db($dbname,$con);
$get=mysql_query("SELECT * FROM Postres ORDER BY postreID ASC");
$option = '';
while($row = mysql_fetch_assoc($get))
{
$option .= '<option id="opcion" value = "'.$row['nombre'].'">'.$row['nombre'].'</option>';
}
?>
<html>
<body>
<?php
$postrevendido = $_POST['postre'];
$preciodelpostre = $_POST['precio'];
if(isset($_POST['agregar'])){
$sql = "INSERT INTO Ventas (id,fecha,postre_vendido,ganancia) VALUES(NULL,NOW(),'$postrevendido','$preciodelpostre')";
$retval = mysql_query($sql);
if(! $retval ) {
die('Could not enter data: <p></p>Agregar otro articulo' . mysql_error());
}
echo "Postre agregado exitosamente!!" . "Volviendo..." . '<p></p>Agregar otro articulo';
mysql_close($conn);
}else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<p>Producto Vendido
<select name="postre" id="postre">
<?php
echo $option . '<p></p>';
?>
</select>
<input name = "agregar" type = "submit" id = "agregar"
value = "Agregar Venta">
</p>
</form>
<?php }?>
</body>
</html>
At the end it only captures the first 3 columns from(id,fecha,postre_vendido,ganancia) and asigns column "ganancia" a value of 0.
You guys have any idea on how to solve this? Thanks in advance!
The price isn't inserting because you don't have a control in your <form> that has the price in it, but I think the way to fix this is actually not to add such a control. In my opinion you really don't need or want the user to enter the price, you should read it from your product table at the time the form is posted. There are various ways to do that. One way is to set it as you are getting the options to show in the <select>.
while($row = mysql_fetch_assoc($get)) {
$option .= '<option id="opcion" value="'.$row['postreID'].'">'
.$row['nombre']
.'</option>';
if (isset($_POST['postre']) && $row['postreID'] == $_POST['postre']) {
$preciodelpostre = $row['price'];
}
} ?>
If you do it this way, be sure to remove the $preciodelpostre = $_POST['precio']; later in the code; since there is not control named 'precio' on the form, this will overwrite the previous value with null which will end up as 0 in your inserted row.

Issue deleting rows in SQL of type varchar

I am trying to create a form that will delete a row in a table based on the attribute a user selects from a drop down list of options. For some reason the first option, (attemptid) which is an int, works, but the other three (which are varchar) do not. The error handling I have set up to debug the script is returning 1 or true, but the row in question is not deleted.
HELP! I have tried everything but am only just learning PHP so imagine I am missing something quite simple.
require_once("settings.php");
$conn = #mysqli_connect($host, $user, $pass, $db);
if ($conn) {
?>
<form method="post" action="delete_attempts.php" name="delete_attempts" id="delete_attempts" >
<label for="deleteby">
<p>Select an option to delete results by:</p>
</label>
<select name="deleteby">
<option value="attemptid">Attempt ID</option>
<option value="firstname">First Name</option>
<option value="lastname">Last Name</option>
<option value="studentid">Student ID</option>
</select>
<p></p>
<input type="text" name="delvalue" placeholder="Value">
<div>
<input type="submit" value="Delete Record" id="submit" />
</div>
</form>
<?php
if (isset($_POST["delvalue"])) {
// get value from form
$delValue = trim($_POST["delvalue"]);
echo $delValue;
// queries to delete record
$queryAttemptId = "DELETE FROM quizattempts WHERE attemptid = '$delValue'";
$queryFirstName = "DELETE FROM quizattempts WHERE firstname = '$delValue'";
$queryLastName = "DELETE FROM quizattempts WHERE lastname = '$delValue'";
$queryStudentId = "DELETE FROM quizattempts WHERE studentid = '$delValue'";
//select which value to search for
if ($_POST["deleteby"] = "attemptid") {
// pass query to database
$result = mysqli_query($conn, $queryAttemptId);
} // end delete attemptid
else if ($_POST["deleteby"] = "firstname") {
// pass query to database
$result = mysqli_query($conn, $queryFirstName);
} // end delete firstname
else if ($_POST["deleteby"] = "lastname") {
// pass query to database
$result = mysqli_query($conn, $queryLastName);
} // end delete lastname
else if ($_POST["deleteby"] = "studentid") {
// pass query to database
$result = mysqli_query($conn, $queryStudentId);
} // end delete student id
echo "this is the result $result";
// if query is successful are found
if ($result) {
echo "<p>Delete operation successful</p>";
} // end if result found
else {
// if no record is found in DB
echo "<p>No records found</p>";
} // end if no result found
} //isset($_POST["attemptid"])
} //$conn
?>
if ($_POST["deleteby"] = "attemptid") {
That should be ==. Your code as written will assign "attemptid" to $_POST["deleteby"] and then return the same value... which is always true. So your other else ifs are never even checked.
Also, your code as written is vulnerable to SQL injection. You're already using mysqli; you should strongly consider using prepared statements.

Categories