Error related to updating quantity in table - php

I need your help to resolve this issue in my script as I am trying to
update a quantity of the product in products table based on
getting information via post from the first page.
Everything seems ok but the quantity is not getting updated in the table.
The table already had some quantity for this product.
Page 1:
$selectP="select prodid, prodname, prodtype from products where prodtype = 'BP'";
$result=mysql_query($selectP) or die (mysql_error());
echo "<form method=POST action=quantupdate.php>";
echo "<center><table border=1 cellpadding=5>";
echo "<tr><td>Select a Product to Update Quantity in Stock </td>";
echo "<td>";
echo "<select size=\"1\" name=\"product_selection\" id=\"product_selection\">";
echo "<option value=\"0\">- Product -</options>";
while($row = mysql_fetch_array($result)) {
echo "<option value='".$row['prodid']."'>".$row['prodname']."</option>";
}
echo "</select>";
echo "<tr><td>Select Quantity </td>";
echo "<td>";
echo "<select size=\"1\" name=\"pq\" id=\"pq\">";
echo "<option value=\"0\">Select Qty</options>";
echo "<option value=\"5\">5</options>";
echo "<option value=\"10\">10</options>";
echo "<option value=\"20\">20</options>";
echo "<option value=\"30\">30</options>";
echo "</select>";
echo "<tr><td><input type=submit name=submit id=submit value='Update Now'></td>";
echo "<td><input type=reset value='Clear Form'></td></tr>";
echo "</table></center>";
echo "</form>" ;
Page 2:
$bprod=$_POST['product_selection'];
$quantity=$_POST['pq'];
if(isset($_REQUEST['product_selection'])) {
$bprod=$_POST['product_selection'];
} else {
echo "Not Working???";//do something about it
}
$updatequantity="UPDATE products
SET prodquantity = ".$quantity." WHERE prodname = ".$bprod;
$exeupdatequantity=mysql_query($updatequantity);
Everything seems ok, no error message but table is not getting updated with the new quantity.
Please help.

It's problem with your update query. You try to update record by prodname, but you pass prodid to it, becouse $_POST['product_selection'] variable contains value of option, which in your case is prodid.
Also,
echo "<option value=\"0\">- Product -</options>";
should be
echo "<option value=\"0\">- Product -</option>";
Also, you should go with what Tomek said, and pass your values to query in apostrophes.
Ultimately, your query should be:
$updatequantity = "UPDATE products SET prodquantity = '".$quantity."' WHERE prodid = '".$bprod."';";

Fix your updating query:
$updatequantity="UPDATE products
SET prodquantity = '".$quantity."' WHERE prodname = '".$bprod."';";
You need to use quotes in strings in MySQL, otherwise they will be treated as column name.
And remember, that using unescaped values from $_POST / $_REQUEST / $_GET is potentially very unsafe.
Use for example mysql_escape_string to escape your values:
$quantity = mysql_escape_string($qunatity);
$bprod = mysql_escape_string($bprod);

Related

PHP & SQL - Update query fails to update value

I'm trying to create a very easy stock managing system. I'm able to show all the items in my table 'parts' and i'm showing the amount in a textbox. However, when i change the value from, for example, 0 to 5 in the textbox and i press my submit button, it doesn't update the stock.
Below is my code, i don't have alot of experience with update querys but i've read about it on php.net, obviously.
<?php
echo "<table width=\"800\" class=\"nieuws\">";
$db=mysqli_connect("localhost","root","","lichtwinkel");
$p=mysqli_query($db, "SELECT * FROM parts WHERE product LIKE 1");
echo "<form method='post' action=''>";
echo "<tr><th></th><th>Onderdeel nummer</th><th>Eigenschappen</th><th>Prijs</th><th>Voorraad</th></tr>";
while ($row = mysqli_fetch_array($p)){
echo "<tr>";
echo "<td><img class='lamp' src='../css/images/".trim($row['partnr']).".png' alt='Geen afbeelding beschikbaar'></td>";
echo "<td>".$row['partnr']."</td>";
echo "<td>".$row['specs']."</td>";
echo "<td>€ ".$row['price']."</td>";
echo "<td><input type='text' id='aantal' name='aantal' value=$row[voorraad] /></td>";
echo "<td><input type='submit' id='update' name='update' value='Update' /></td>";
echo "</tr>";
}
echo "</table>";
if(isset($_POST['aantal']) && $_POST['update']) {
$y = $_POST['aantal'];
$p=mysqli_query($db, "UPDATE parts SET voorraad = '$y' WHERE partnr = $row[0]");
}
echo "</form>"
?>
Simply said, what i'm trying to achieve is the following:
Whenever i change the value displayed in the texbox, and i press my submit button, i want it to update the value in the database.
Does anyone know what i'm doing wrong? Any ideas? Articles i should read?
All help would be appreciated.
Thank you.
As i see, you were doing it wrong at all.
First you can't use form tag within more then one td element.
You were didn't close the form tag, only at end. (So if it loops 6 times, you will have 6 forms open, but one ended!).
At update, you're selecting row[0] - it's outside of loop with rows?
Even if you update it, it will show wrong results again. Update should be above selects! So it picks up newly updated value.
What to do:
First make one form for all updates.
Use your submit button to have value DATABASE_ID.
Make the name of "aantal" to "aantalDATABASE_ID".
At submit check for $_POST['update'], and use it's value (DATABASE_ID) to get input $_POST["aantal".$_POST['update']].
Do update, you have all you need.
Example:
<?php
echo "<form method='post' action=''>";
echo "<table width=\"800\" class=\"nieuws\">"
$db=mysqli_connect("localhost","root","","lichtwinkel");
if(isset($_POST['update']) && !empty($_POST['update'])) {
$y = $_POST['aantal'.$_POST['update']];
$p=mysqli_query($db, "UPDATE parts SET voorraad = '".$y."' WHERE partnr = '".$_POST['update']."'");
}
$p=mysqli_query($db, "SELECT * FROM parts WHERE product LIKE 1");
echo "<tr><th></th><th>Onderdeel nummer</th><th>Eigenschappen</th><th>Prijs</th><th>Voorraad</th></tr>";
while ($row = mysqli_fetch_array($p)){
echo "<tr>";
echo "<td><img class='lamp' src='../css/images/".trim($row['partnr']).".png' alt='Geen afbeelding beschikbaar'></td>";
echo "<td>".$row['partnr']."</td>";
echo "<td>".$row['specs']."</td>";
echo "<td>€ ".$row['price']."</td>";
echo "<td><input type='text' id='aantal' name='aantal".$row[0]."' value='".$row[voorraad]."' /></td>";
echo "<td><input type='submit' id='update' name='update' value='".$row[0]."' /></td>";
echo "</tr>";
}
echo "</table>";
echo '</form>';
?>
After all, take care about SQL Injections. "aantal" value is user input. As the submit value can be changed.

MSSQL and PHP: Select specific row based on which button is clicked

I am making a website for a mock book database using MSSQL where users can search for different books and select particular books that they might like to add to a list of favorites under their account name. The problem I am having is that I have no idea how to differentiate which book selection they want to add to their favorites because I can't figure out how to set the ISBN of the book, which uniquely identifies it, to a php session variable. If anyone can shed some light on this I would appreciate it, have been trying to figure it out all day.
//Set up connection
$connection = mssql_connect("$hostName", "$sqlUsername", "$sqlPassword")
or die("ERROR: selecting database server failed.");
//Select database
mssql_select_db($databaseName, $connection)
or die("ERROR: Selecting database failed");
//Search to run if searching for book title
if(isset($_GET['searchBook'])){
$searchBook = $_GET['searchBook'];
$query = "SELECT BOOK.ISBN, Title, Author, Publisher, NumberOfPages, Language, LocationName, ListPrice FROM BOOK, PRICE, LOCATION WHERE Title LIKE '%$searchBook%' AND BOOK.ISBN = PRICE.ISBN AND PRICE.LocationID = LOCATION.LocationID";
}
//Search to run is searching for a book author
if(isset($_GET['searchAuthor'])){
$searchAuthor = $_GET['searchAuthor'];
$query = "SELECT BOOK.ISBN, Title, Author, Genre, Publisher, NumberOfPages, Language, LocationName, ListPrice FROM BOOK, PRICE, LOCATION WHERE Author LIKE '%$searchAuthor%' AND BOOK.ISBN = PRICE.ISBN AND PRICE.LocationID = LOCATION.LocationID";
}
//Store query result
$query_result = mssql_query($query, $connection)
or die( "ERROR: Query is wrong");
//Set up table to display search results
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><input name=\"".$line['index']."\" type=\"submit\" value=\"Add To Favorites\"></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
Not sure if this is relevant but the following code is my best attempt at getting the value of ISBN that corresponds to the row of the button being clicked, which doesn't exactly work like I had hope.
//Get the ISBN
$data = mssql_fetch_assoc($query_result);
$ISBN = $data['ISBN'];
echo $ISBN;
Here is the code for my addFavorite.php which is where the form action is set to. This is the file that needs to know what user is adding a book as a favorite AND what book they are adding to that list.
//Set up connection
$connection = mssql_connect("$hostName", "$sqlUsername", "$sqlPassword")
or die("ERROR: selecting database server failed.");
//Select database
mssql_select_db($databaseName, $connection)
or die("ERROR: Selecting database failed");
$User = $_SESSION['userID'];
//Set up query
$query = "INSERT INTO FAVORITES VALUES(\"$User\",\"**I NEED A SESSION VARIABLE OR SOMETHING TO GO HERE\")";
//Store query result
$query_result = mssql_query($query, $connection)
//or die( "ERROR: Query is wrong");
Any help would be much appreciated. I know it's alot of information and if there is anything that doesn't make sense or I have forgotten to provide please let me know. Thanks.
EDIT
I have tried using the BUTTON instead of using INPUT but the value of the button is not setting to anything for some reason.
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records **PROBLEM IN HERE since $line['ISBN'] returns nothing**
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><button name=\"FavoriteButton\" type=\"submit\" value=\"".$line['ISBN']."\">Add To Favorites</button></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
EDIT 2
Finally got it working, thanks to everyone for helping! Partial code that was problematic posted below in working condition.
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><button name=\"FavoriteButton\" type=\"submit\" value=\"".$line[0]."\">Add To Favorites</button></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
Use a BUTTON-element instead of the INPUT-element. That way, you can use the 'value'-attribute of this element to pass the correct value.
echo "<td><button name=\"$line['index']\" value=\"$line['ISBN']\" type=\"submit\">Add to favorites</button></td>";
Although I would suggest using AJAX instead of the above approach for this: use the onclick event from a button to execute javascript that calls a seperate php-file and passes the correct ISBN-number. This is then added to the database and your original page should be refreshed or part of the page reloaded.

Show "Select a ..."on dropdown menu

I have a dropdown menu created with the code below which fetches all brands from a brands table. It uses a while loop thus showing all on the menu starting alphabetically (i.e., Adiddas and so on). Therefore I don't list them as individual <options> line by line.
echo "<form action=\"type.INC.php\" method=\"get\">\n";
echo "<select name=\"brand\">\n";
$stmt = mysqli_stmt_init($hook);
if($stmt=mysqli_prepare($hook,"SELECT brandid, brandname FROM brands WHERE brandid "));
{
mysqli_stmt_bind_param($stmt,"i", $brandid);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $brandid, $brandname);
while(mysqli_stmt_fetch($stmt))
{
$brandname = htmlspecialchars($brandname, ENT_QUOTES, 'UTF-8');
echo "<option value=\"$brandid\">$brandname </option>";
}
echo "</select>\n";
echo "<input name=\"submit\" type=\"submit\" id=\"brandid\" value=\"submit\" />\n";
echo "</form> \n";
How can I show the sentence "SELECT A BRAND" to appear as the default first value? Should I just enter "SELECT A BRAND" into my brands table and assign a primaryID of zero to it?
Any better way to do this?
All of my searches regarding this question result in topics relating to the 'select=selected attribute'.
Thanks,
Jen
Just add it manually before the loop:
echo "<form action=\"type.INC.php\" method=\"get\">\n";
echo "<select name=\"brand\">\n";
// Select a brand, empty value:
echo "<option value=\"\">(SELECT A BRAND)</option>";
$stmt = mysqli_stmt_init($hook);
if($stmt=mysqli_prepare($hook,"SELECT brandid, brandname FROM brands WHERE brandid "));
{
mysqli_stmt_bind_param($stmt,"i", $brandid);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $brandid, $brandname);
while(mysqli_stmt_fetch($stmt))
{
$brandname = htmlspecialchars($brandname, ENT_QUOTES, 'UTF-8');
echo "<option value=\"$brandid\">$brandname </option>";
}
echo "</select>\n";
echo "<input name=\"submit\" type=\"submit\" id=\"brandid\" value=\"submit\" />\n";
echo "</form> \n";
Add
echo "<option>SELECT A BRAND</option>";
as the third line of your code.

How do I update the Table for entering marks of students foreach student Id each mark in php mysql

Hi I have senario where i need to update the MySQL table which has student ID and Student Marks. Now the Student ID is unique here. How do I use only one form to update all the students marks.
$result= mysql_query("SELECT fname,usn FROM student where branch='$branch' and section='$section' and semester='$semester'") or die(mysql_error());
echo "<form action=\"marks.php\" method=\"POST\">";
echo "<table border='6' width='500' cellspacing='10' cellpadding='10' style='font-size:14px'>";
echo "<caption>";
echo "<b style='font-size:18px'>Internal</b> ";
echo "<b style='font-size:18px'>";
echo $internal;
echo "</b>";
echo " <b style='font-size:18px'>marks of</b> ";
echo "<b style='font-size:18px'>";
echo $subject;
echo "</b>";
echo "</caption>";
echo "<tr><th>USN</th><th>FNAME</th><th>MARKS</th></tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['usn'];
echo "</td><td>";
echo $row['fname'];
echo "</td><td>";
echo "<input name=\"internal\" type=\"text\" value=\"\" >";
echo "</td></tr>";
echo "</table>";
echo "<input name=\"update\" id=\"update\"type=\"submit\" value=\"submit \"align=\"middle\" >";
Each time you print out the input field for the student mark, you could print a name attribute for the input field that uniquely identifies it - using an integer counter, for example, from 0 to N-1, where N is the number of students. You could also pass a hidden input field with the total number of students. The PHP code that receives the data then uses the hidden input field to loop over the input fields in the form data.
For example, if the input fields end up being named FIELD0 ... FIELD20, then the hidden input field has value 21, so the PHP code simply says this:
$marks = array();
for ($i = 0; $i < $NUMOFMARKS; $i++) {
$marks[] = $POST['FIELD' . $i];
}
Then build your SQL query from the array of marks.

update MySQL resultset through user-interaction and make the changes global for the application

I fetching a result set from a MySQL table and displaying it on the web page as under:
<?php
$link = mysql_connect(....);
mysql_select_db(....);
$sql = "select * from products where category = '" .$_POST['prod_cat']. "'";
$rs = mysql_query($sql, $link);
echo "<form name='prodselect' action='prodlist.php' method='post'>";
echo "<table>";
$rowcount = 1;
while ($row = mysql_fetch_array($rs))
{
echo "<tr>";
echo "<td>" .$row['product_name']. "</td>";
echo "<td><input type='checkbox' name='line_" .$rowcount. "'></td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
?>
This displays the list of products with checkbox for every product row.
The user will select products using the checkboxes.
I want to display / save the selected products in the "Products for Purchase" list on another web page.
Please help me out.
Thanks.
I can suggest you to create the checkbox like this:
echo "<td><input type='checkbox' name='products[]' value='" .$row['product_id']. "'></td>";
then on the prodlist.php you can get the array $_POST['products']

Categories