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.
Related
I'm sorry about my question, but I'm starting with PHP and I want to ask you for a help with my problem.
In my web application I work with a table, which has a dynamic count of rows based on the number of rows in a source table in MySQL database. In the application should be a checkbox in each row of the table. After clicking on the submitt button there should be update of records in the source table and it should be update just of these records where the checkboxes were checked.
The table in the application looks simillar like in the picture.
The primary key in the source table is in the column NUMBER. As a first try I simulated that after clicking on submitt button there will be shown the msgbox with the values from the column NUMBER for the rows, where the checkboxes were checked.
<html>
<head>
<title>APLICATIONa</title>
<script type="text/javascript">
function GetSelected() {
//Reference the Table.
var grid = document.getElementById("Table");
//Reference the CheckBoxes in Table.
var checkBoxes = grid.getElementsByTagName("INPUT");
var message = "\n";
//Loop through the CheckBoxes.
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
var row = checkBoxes[i].parentNode.parentNode;
message += " " + row.cells[1].innerHTML;
message += "\n";
}
}
//Display selected Row data in Alert Box.
alert(message);
}
</script>
</head>
<body>
<?php
$values = mysql_query("SELECT * FROM table_03_2020");
echo "<br><form action='main.php' method='POST'>";
echo "<input type='submit' name='button' value='Get Selected' class='btn btn-primary' onclick='GetSelected()' />";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
echo "<td><input type='checkbox' name='cbox[]' ></td>";
echo "<td><font color='red'>".$zaznam["number"]."</font></td>";
echo "<td>".$zaznam["name"]."</td>";
echo "</tr>";
endwhile;
echo "</table><br>";
echo "</form>";
?>
</body>
</html>
The msgbox is just an illustration. Instead of msgbox, I need that after clicking on the submit button, there should be an update for these records in the source table, where the checkboxes were selected (so of these records, which are now shown in the msgbox). So I need something like:
"UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
There'll be also a second submit button and after clicking on it, there should be another different update. So after clicking on the second button, I need something like:
"UPDATE table_03_2020 SET column1 = 'ab' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
I'm sorry if my question is not so clear, but I'd really appreciate any help.
Thank you very much.
Add key values with the number to the cbox form variable:
echo "<td><input type='checkbox' name='cbox[" .$zaznam["number"]. "]' ></td>";
Then use the following PHP to get the number list.
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
The addslashes function is for SQL Injection protection.
This will create a list with comma separated numbers.
Than, you can insert it in the the SQL query.
UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('. $checked_list .')
If you assign a value to the checkboxes, like this:
<input type='checkbox' name='cbox[]' value='{$zaznam["number"]}' >
When the form is submitted the cbox variable will contain an array of these numbers, which means that you can process them like this:
<?php
include 'db.php'; #your database connection!!!
$sql='update table_03_2020 set `column1`="XY" where `column2` in ( ? )';
$stmt=$db->prepare( $sql );
$ids=implode(',',$_POST['cbox']);
$stmt->bind_param('s',$ids);
$stmt->execute();
?>
Note that the above has not been tested so there might be errors but I hope it'll give the idea.
Thank you, I tried to improve the part of the code to:
echo "<input type='submit' name='buttonupdate' value='Get Selected' >";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
if ($_POST["buttonupdate"]) {
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
}
echo "<td><input type='checkbox' name='cbox[" .$zaznam["cflot"]. "]' ></td>";
It didn't work, there was no update. Did I edited the code incorrectly?
Actually I forgot to mention the second button, so I edited my first post. Would it be possible to distinguish between the first and the second button? Thank you very much for any help.
I want to create a page, where I can create Keys, and save them in a databank, but I got some problems.
There is a textfield, where you can write in, how many keys you want to create. For example I write 5 in, but it does only 3 entrys in the databank, but down in the code is an echo command, which says that he did it 5 times, here is a screenshot:
Also, what I noticed is, that the website is doing max 3 entrys in the databank, for example I write 10, and he still only does 3 entrys.
If I write only 1-3 keys, the while-loop is working.
echo "<p><a href='key.php'>Betakey administration</a></p>";
echo "<form action='#' method='POST'>";
echo "<input type='number' name='numberkeys' placeholder='Number of Keys'>";
echo "<br>";
echo "<input type='submit' name='createkey' value='Create Key'>";
echo "<input type='submit' name='keyanzeigen' value='Show all Keys'>";
echo "<input type='submit' name='unusedkeys' value='Show all unused Keys'>";
echo "<input type='submit' name='usedkeys' value='Show all used Keys'>";
echo "</form>";
$createdkeys=0;
if(isset($_POST['createkey'])){
$minus= array(5,10,15);
while($createdkeys<$_POST['numberkeys']){
//creation of the keys
for($i=1;$i<20 ;$i++){
if(in_array($i,$minus)){
$key=$key."-";
}
else{
$key=$key.mt_rand(0,9);
}
//the key looks like this: 1234-5678-1234-5678
}
//here it checks, if the key already exists
$check = mysqli_query($db,"SELECT keyy FROM keyys WHERE keyy='$key'");
$check = mysqli_fetch_array($check);
//if the code not exists, the website will insert the key in the databank
//the website will echo the variable $createdkeys and increase the variable $createdkeys by one
if(!isset($check)){
$createdkeys= $createdkeys+1;
echo "<p>".$createdkeys."</p>";
mysqli_query($db,"INSERT INTO keyys VALUES('$key','NO')");
}
}
}
Hi I'm looking to insert a varible into a submit buttons name when I echo it via a loop so that each button has a unique name
$x=0;
$sql = "SELECT * FROM userstats ORDER BY RAND() LIMIT 5; ";
$result = mysqli_query($link,$sql);
echo ("<table>");
echo ("<tr>");
echo ("<th>Name</th>");
echo ("<th>Level</th>");
echo ("<th>Stats</th>");
echo ("<th>Win Chance</th>");
echo ("<th>Action</th>");
echo ("</tr>");
while($row = mysqli_fetch_assoc($result)){
if($row['username'] !== $_SESSION['username']){//add so it dosent put duplicates
echo("<tr>");
echo("<th>".$row['username']." </th>");
echo("<th>Level: ".$row['Level']." </th>");
echo("<th>Player Stats:".$row['Attack']."/".$row['Defence']." </th>");
echo("<th>Win Chance: ");
echo(CalculateWinChance($link,$row['Defence']));
echo("<input type='hidden' name='".$x."hidden1' value='".$row['Defence']."' />");
echo("<input type='hidden' name='".$x."hidden2' value='".$row['username']."' />");
echo("<th><input type='submit' name = 'Attack_Btn".$x."' onclick = 'BattlePlayers()' value ='Attack'></th>");
echo("</tr>");
$x=$x+1;
}
}
echo ("</table>");
I tried the above code but it does not change the name attribute? What am I doing wrong here?
you can put that as an answer can ill accept it :) – GregHBushnell
Posting from comments:
"$ is not empty its prining as expected 01234" - The leading zero is treated as an octal, that's why it's failing. . – Fred -ii
thank you very much that solved it :) what is an octal ? – GregHBushnell
References:
http://php.net/manual/en/language.types.integer.php
https://en.wikipedia.org/wiki/Octal
Footnote:
echo is a language construct and not a "function" per se. So, you can safely omit all of the (), since that's just more code than needed really.
Reference:
http://php.net/manual/en/function.echo.php
I am on the process of modifying old code. I want to have set of input fields as rows in a table with Update button along with them. Below code is included in seperate ajax_edit_designation.php page which is being called by the edit_designation page. When the update is selected it should enter the new value to the database. The script required for it is written in the edit_designation.php page.
I would like to know whether what I am doing is correct or wrong. Because for some reason it doesn't carryout required action when the 'Update' button is selected. In the browser console it doesn't throw any exceptions either. What am I doing wrong?
Is it something that happen due to some kind of version issue? Or am I really doing something wrong?
echo "<table>";
while($row_tay = mysql_fetch_array($result_tay)){
$temp++;
$designation = $row_tay['designation'];
$designationID = $row_tay['designationID'];
echo "<tr ";
if($temp%2 == 1)
{
echo " bgcolor =\"#F3F3F3\" ";
}
else
{
echo " bgcolor =\"#DBDBDB\" ";
}
echo " >";
echo "<form id=\"myform".$designationID."\" method=\"post\">";
echo "<td class=\"bodytext\">";
echo "<input type=\"text\" id=\"designation\" size=\"50\" value=\"".htmlentities($designation)."\" name=\"designation\" />";
echo "</td>";
echo "<td width=\"120\" align=\"center\">";
echo "<input name=\"addcat\" id=\"addcat\" type=\"submit\" value=\"Update\" class=\"Submit_Button_long\">";
echo "<input type=\"hidden\" name=\"designationID\" value=\"".$designationID."\">";
echo "</td>";
echo "</form>";
echo "</tr>";
}
echo "</table>";
Because, same thing happened to me in another page also, where I added seperate form tags as above. In that case, previously it had given all the Update buttons under same tag. When I remove that earlier form tag and add only the new tags as above, they didn't work as now. But if I add that previously available tag, by wrapping all those forms created with the table, Update buttons worked. What could be the reason. Please help?
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);