edit product page with id feature - php

On a web app i'm making, I have an edit page which is obviously where users edit info on already existing products, it uses PHP/ MySQL. My edit page is ALMOST working exactly how I want it too. I have a drop-down populated from the SQL database, and I can edit the product info via the text-boxes. The only problem I have is that I do not know how to edit the products via the ID which changes as the products are selected.. I instead have to manually set a static value in the PHP code, I was just wondering how I could do this? I'm thinking GET could be used but not entirely sure.. I'll post pictures and code below.. thanks.
The ID changes to the corresponding product ID as I select a product from the dropdown
As you can see I have to type in the ID in the php..
so basically i was trying to get it to change the product to edit as i select them from the dropdown..
hope i wasnt too confusing, thanks!
$conn = new mysqli('', '', '', '')
or die ('Cannot connect to db');
$result = $conn->query("select ID, NAME from PRODUCTS");
?><div align="left"><?
print "<h3>EDIT PRODUCT</h3>";
print "<strong>SELECT PRODUCT:</strong>";
print "<br><br>";
print "<form method='GET' id='frm_product'>";
print "<select name='ID' OnChange='$(\"#frm_product\").submit();'>";
while ($row = $result->fetch_assoc())
{
print "<option value='$row[ID]'>$row[NAME]</option>";
}
print "</select>";
print "</form>";
?>
<form method='POST'>
<h3>PRODUCT:</h3>
<input type='textbox' name='product' value='<?php echo $product['product'] ? >'>
<h3>BARCODE:</h3>
<input type='textbox' name='barcode' value='<?php echo $product['barcode']; ?>'>
<h3>TYPE:</h3>
<select name="type">
<option value=""></option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<br><br>
<input type='submit' value='Save Changes' name=submitform>
</form>
<?
if (isset($_POST['submitform']))
{
$namechange = $_POST[product];
$barcodechange = $_POST[barcode];
$typechange = $_POST[type];
$sql = "UPDATE PRODUCTS SET
NAME='$namechange'
,BARCODE='$barcodechange'
,TYPE='$typechange'
WHERE ID='79'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
}

Cant you set:-
$productID = $_GET['ID'];
And then change the 79 on the update script to $productID?
Hopefully I understood the question.

You can do something like this in javascript.
redirect to the product page each time the user selects an option.
<select id="products" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<script>
function myFunction() {
var id = document.getElementById("products").value;
window.location.href = "/linkto/product.php?"+id;
}
</script>
If you don't want to reload the page each time you can use jQuery Ajax and JSON

If I get you right you want to edit the entries in the databse which belong to a special ID, right? As you tried with $_GET you must add this to your sql query aswell:
[...]
$typechange = $_POST['type'];
// end of your old code
// start of new code
$id = $_GET['ID'];
// modified sql query
$sql = "UPDATE PRODUCTS SET NAME='$name', BARCODE='',TYPE='' WHERE ID='$id'";
// rest of your old code
[...]
Note: It´s not recommended to use user input without validating. A user can change the values for any existing ID by just manipulating the $_GET parameter in your url. You should validate the users input before processing.

Related

dependent dynamic dropdown in php

Here I have two dependent drop downs.
First drop down is displaying all accounts(name and id).
<select name="account" id="account" class="input-name">
<?php
$query = "SELECT id,name FROM account";
$results = mysqli_query(con, $query);
while($account = $results ->fetch_assoc()){
?>
<option value="<?php echo $account["id"]; ?>"><?php echo $account["name].'-'.$account["id"];?</option>
<?php } ?>
</select>
In second drop down I need to display selected account users.
<select name="extension" id="extension" class="input-name">
<?php
$query = "SELECT ext FROM user WHERE account=100"; //Query for users for selected account.
$results = mysqli_query($con, $query);
while($user= $results ->fetch_assoc()){
?>
<option value="<?php echo $user["ext"]; ?>"><?php echo $users["ext"];?></option>
<?php } ?>
</select>
How can I filter users according to select company. Need help.
You may reload page after first value was selected and load page with second param. for example
<select onchange="window.location.href='some url with some value?select_value=' + this.value">...options...</select>"
Or if you do not want to reload page you can use AJAX. send request with ajax to server and replace options in second select.
with jquery
$('select.first-select').change(function(){
var value = $(this).val();
$.get('get-account', { val: value }, function(){ ...replace options... })
})
You can do it by using Jquery ajax request. Write an onchange method on first dropdown. On change take the id of selected account and pass it to your query for selecting users.Return all the users and display it to your users dropdown.

Filtering my postgreSQL table using drop down box

The Problem
I am having trouble filtering my table, no errors are coming up so I am unsure why it isn't working. I am wondering whether it is to do with the placement of SQL code or whether the submit button isn't coded correctly... Or even if the ive programmed it all wrong haha.
Expected Outcome
What I expect to see when press submit is for the table to change to what ever it was that submitted. For exmple, in the drop down box there is an option for 'Canned' food, if I was to press this I would expect to see the table change, showing only canned food.
What the actual outcome is
Nothing seems to be happening, and with no errors, i'm completely unsure as to why.
Here is the code for the drop down box
I am unsure whether this is the correct form for what I am trying to do. I want to stay on the same page, I only want to affect the table.
<form action="database.php">
<select name="category" id="category">
<option value="Alcoholic">Alcohol</option>
<option value="Canned">Canned Food</option>
<option value="Dairy">Dairy</option>
<option value="Dessert">Dessert</option>
<option value="Frozen">Frozen Food</option>
<option value="Fruit">Fruit</option>
<option value="Junk Food">Junk Food</option>
</select>
<input type="submit" name="submit" value="Search"/>
</form>
Here is the code for the table and the SQL commands
<?php
$conn = pg_connect("host=db.dcs.aber.ac.uk port=5432
dbname=teaching user=csguest password=********");
// Empty var that will be populated if the form is submitted
$where = '';
if (isset($_POST['submit'])) {
if (!empty($_POST['category'])) {
// Where conditional that will be used in the SQL query
$where = " WHERE Category = '".pg_escape_string($_POST['category'])."'";
}
}
$res = pg_query($conn, "SELECT Foodtype, Manufacturer, Description, Price
FROM food " . $where . " ORDER BY Category ASC");
echo "<table id=\"myTable\" border='1'>";
while ($a = pg_fetch_row($res)) {
echo "<tr>";
for ($j = 0; $j < pg_num_fields($res); $j++) {
echo "<td>" . $a[$j] . "</td>";
}
echo "<td><form id='cart' name='cart' method='POST' action='addToBasket.php'>
<input type='submit' name='Select' id='Select' value='Add To Basket'>
</form></td>";
echo "</tr>\n";
}
echo "</table>\n";
$Alcoholic = pg_query("SELECT Foodtype, Manufacturer,
Description, Price FROM food WHERE Category = 'Alcoholic'");
$Canned = pg_query("SELECT Foodtype, Manufacturer,
Description, Price FROM food WHERE Category = 'Canned'");
?>
The last two SQL statements above are supposed to filter the table, there will one for each of the drop down options
Since the discussion on the comments lead to the solution, I'm adding it here:
Your problem is that you defined a form without a method which means that it will be by default GET and in your code you are trying to get POST variables so change your form to:
<form action="database.php" method="post">

keep php result as content in div

EDIT!!! : LINK = http://i299291.iris.fhict.nl/PHP31/DV3/DV3.php
My problem:
I've made two dropdown boxes with several options. The php code is working and the query gets the right result from the database. But now i want to compare two options.
This is what i've got so far, the problem now is the entire page refreshes when i enter the second value from the other dropdown box.
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form id = "leftDropdown" action= "" method="post">
<select name="objectLinks">
<option value="school">School</option>
<option value="klas">Klas</option>
<option value="geslacht">Geslacht</option>
<option value="lengte">Lengte (CM)</option>
<option value="kg">Gewicht (KG)</option>
<option value="opleiding">Opleiding Ouders</option>
<option value="leeftijdJaar">Leeftijd</option>
<option value="interventie">Deelname interventie?</option>
<option value="pestenVoor">Pestincidenten voor interventie</option>
<option value="pestenNa">Pestincidenten na interventie</option>
<option value="bmi">BMI waarde</option>
<option value="overgewicht">Overgewicht</option>
<option value="allochtonenPerc">Percentage Allochtonen</option>
</select>
<input type="submit" name="sendLinks" value="Go!">
</form>
<form id = "rightDropdown" action= "" method="post">
<select name="objectRechts">
<option value="school">School</option>
<option value="klas">Klas</option>
<option value="geslacht">Geslacht</option>
<option value="lengte">Lengte (CM)</option>
<option value="kg">Gewicht (KG)</option>
<option value="opleiding">Opleiding Ouders</option>
<option value="leeftijdJaar">Leeftijd</option>
<option value="interventie">Deelname interventie?</option>
<option value="pestenVoor">Pestincidenten voor interventie</option>
<option value="pestenNa">Pestincidenten na interventie</option>
<option value="bmi">BMI waarde</option>
<option value="overgewicht">Overgewicht</option>
<option value="allochtonenPerc">Percentage Allochtonen</option>
</select>
<input type="submit" name="sendRechts" value="Vergelijk!">
</form>
<div id = "leftDiv">
<?php
include_once 'dv3ToDB.php'; // connect to database *local or at school's server*
session_start();
if(isset($_POST['sendLinks'])){
$selectedValLinks = $_POST['objectLinks'];
// echo "Jij selecteerde: ".$selectedVal;
echo "<script>console.log('$selectedValLinks');</script>";
// $_SESSION["valLinks"] = $selectedValLinks;
// echo $_SESSION["valLinks"];
$query = "SELECT ($selectedValLinks) FROM pesten ORDER BY ($selectedValLinks) * 1";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Gevonden data in ".$selectedValLinks.": " . $row["$selectedValLinks"] . "<br>" ;
}
}else{
echo "0 results";
}
}
?>
</div>
<div id = "rightDiv">
<?php
if(isset($_POST['sendRechts'])){
$selectedValRechts = $_POST['objectRechts'];
// echo "Jij selecteerde: ".$selectedVal;
echo "<script>console.log('$selectedValRechts');</script>";
// $_SESSION["valRechts"] = $selectedValRechts;
// echo $_SESSION["valRechts"];
$conn = mysqli_connect($host,$username,$password,$database)
or die("verbinding mislukt:".mysqli_connect_error());
$query = "SELECT ($selectedValRechts) FROM pesten ORDER BY ($selectedValRechts) * 1";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Gevonden data in ".$selectedValRechts.": " . $row["$selectedValRechts"] . "<br>" ;
}
}else{
echo "0 results";
}
}
?>
</div>
</body>
</html>
i'm running it local now, let me know if you need me to build a database online to help me out.
How can i code it so the PHP output stays in de left DIV and/or the right DIV?
Thank you so much guys and girls! :)
If you need to use only PHP, without any JavaScript (which could allow you to display the result from the database after selecting each option without reloading the page), I'd suggest that, after submitting one form, you add it's result as a hidden input for the other form, so you could read this variable after submitting the 2nd form.
Like this:
<? // Your code for getting the result of the 1st form above returns a variable $res1
// Now insert this into the 2nd form:?>
<input type="hidden" name="stored2" value="<?echo $res1;?>"/>
This way, you can read the variable $_POST["stored2"] after submitting the 2nd form to get what the 1st form returned before.
Do the same for the 1st form to store the results of the 2nd form if it was filled first.
This way, you can compare the results of submitting 2 forms while using only PHP.
EDIT:
You'll need to place all the database requests before the forms to use this method, and just echo the result in the div later.
You want to make a new <iFrame> and then set that <iFrame>'s id as the target for your form.
e.g.:
<form ... target="newframe">
...
</form>
<iFrame id="newframe"></iFrame>
As Lal mentioned you don't need two forms, just one will work.
You need some code that updates the option to selected, if you don't want it to "stick" on page refresh.
Further reading here;
http://www.w3schools.com/tags/att_option_selected.asp
and here
html select option SELECTED
Even try Jquery;
http://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu

get value from combo box to php

this is my combo box page coding:
<?php
echo "<form method=post align=center>
<div id=myDiv>
<select name=userselect>
<option value=empty></option>
<option value=Confirm> Confirm </option>
<option value=Processing> Processing </option>
<option value=Pending> Pending </option>
<option value=Cancelled> Cancelled </option>
</select>
<button type=button name=combobox value=combobox onclick=loadXMLDoc()>Update</button>
</div>
</form>";
?>
this is my php code (another page):
<?php
if (isset($_POST['combobox']))
{
$userselect = $_POST['userselect'];
echo $userselect;
}
?>
if user select one value in combo box that value should store in db and then display what they are selected. for example if user select CONFIRM option that value stored in db after that it display CONFIRM instead of that combo box form and button. Here i can stored the combo box values in db successfully. thats not a problem and then here i used ajax method to show the msg instead of button place. Now, i want what user select it should display the same value. check these above coding and reply me ur suggestions...
Replace Your code with this:
<?php
//Connect To your Database File..
//After Connecting To Databse
$combo = mysqli_real_escape_string('yourconnectionlink', $_POST['userselect'])
echo "<form method='post' action='youractionfile.php' align='center'>
<div id='myDiv'>
<select name='userselect'>
<option value='empty'></option>
<option value='Confirm'> Confirm </option>
<option value='Processing'> Processing </option>
<option value='Pending'> Pending </option>
<option value='Cancelled'> Cancelled </option>
</select>
<input type='button' name='combobox' value='combobox'>Update</button>
</div>
</form>";
//Insert Data into Database File
if($_POST['userselect'])) {
if(isset($_POST['userselect'])) {
$query = "INSERT INTO tablename (your field names) VALUES ('".$combo."')";
$res = mysqli_query('yourconnectionlink', $query);
echo '1 row inserted';
}
}
?>
finally i got it what i want. without using ajax method i can store the data to db and then combobox, button hide permanently if once we updated the status. this is my final coding...
if ( $a_row['status'] != 'empty' ) {
echo "\t<td>" . $a_row[$status] . "</td>\n";
}
else {
echo "\t<td><form action=statusdb.php method=post>
<select name=update>
<option value=empty></option>
<option value=Confirm>Confirm</option>
<option value=Processing>Processing</option>
<option value=Pending>Pending</option>
<option value=Cancelled>Cancelled</option></select>
<input name=id type=hidden value='".$a_row['slno']."';>
<input type=submit value=Update>
</form>
</td>\n";
}
statusdb coding:
if (isset($_POST['id']))
{
$id = mysql_real_escape_string($_POST['id']);
$update= mysql_real_escape_string($_POST['update']);
$sql = mysql_query("UPDATE guest_details SET status = '$update' WHERE slno = '$id'");
if(!$sql)
{
die("Error" .mysql_error());
}
}
i posted another question (php combobox & button should hide once updated into mysql db and show success message instead of combobox & button place.). i got help from that answer... so, only i posted the correct answer here..

Select from drop-down menu and reload page

I've got a table that populates data from a MYSQL database and populates a drop-down menu from the same database. I have the drop down menu and table just fine, I would like to be able to choose which data I show in the table however.
<select name = 'peer-id' method='post' style = 'position: relative'>
<?php
while ($content = mysql_fetch_array($peer)) {
echo "<option value='" . $content['Peer'] . "'>" . $content['Peer'] . "</option>";
}
$results = mysql_query("SELECT Destination FROM rate ");
?>
</select>
That's what I have for the select box. How can I get the choice from that and save that as a variable and refresh the table data?
I need to clarify that this will change that current data
#Data#Data#Data
#Data#Data#Data
#Data#Data#Data
Then choose drop down choice and I want it to show new data
#Data2#Data2#Data2
#Data2#Data2#Data2
#Data2#Data2#Data2
So it's going to need to load a new page or refresh some how because it's changing via PHP and not javascript.
I think form may be better, for example
<form id="myform" method="post">
<select name = 'peer-id' style = 'position: relative' onchange="change()">
<option value="1">12</option>
<option value="2">15</option>
<option value="3">16</option>
<option value="4">18</option>
</select>
</form>
<script>
function change(){
document.getElementById("myform").submit();
}
</script>
In the above code, whenever you change the value of select, it will post to the backend, then according to the posted value, you can do want you want, to get the peer-id in php, you can use the following code
$peer-id = $_POST['peer-id'];
Hope helps!
apply this code in select tag hope this works
<select onchange="location = this.options[this.selectedIndex].value;" style="text-decoration:none;">
<option value="customers.php"></font></option>
</select>
insted of the static options, you can do it like this :) here you get all the options from the database. Just replace it with the static options
$peer = mysql_query("SELECT Peer FROM rate Group By Peer Where peer = 'variable'");
$result_peer = mysql_query($peer);
if($result_peer){
while($row_peer = mysql_fetch_array($result_peer)){
echo'<option value='.$row_peer['Peer'].'>'.$row_peer['Peer'].'</option>';
}
I agree in using form, and with this you can echo back onto the page with a submit button (code tested):
<form id="myForm" method="POST">
<select name="select" onchange="<?php echo $_SERVER['PHP_SELF'];?>">
<option value="N">No</option>
<option value="Y">Yes</option>
</select>
<input type="submit" name="formSubmit" value="Submit" >
</form>
<?php
if(isset($_POST['formSubmit']) ){
$var = $_POST['select'];
$query = "SELECT * FROM table_name WHERE DesiredField='$var'";
$result = mysql_query($query)
or die(mysql_error());
while($row = mysql_fetch_array($result)){
$var2 = $row['FieldName'];
echo "First field: " . $var2 . "<br>";
// and so on for what you want to echo out
}
}
?>

Categories