SQL Update Query doesnt' Update when using Dropdown list - php

I have 2 tables: product (id, name, quantity, c_id) and product_category (cat_id, cat_name).
I have the option to update the existing products. When I change the name and the quantity it works just fine, but when I try to change the product category the c_id doesn't change to the new one.
The code from the update page (update.php):
<?php
include 'database.php';
$id = $_POST['productId'];
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM product where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['name'];
$quantity = $data['quantity'];
Database::disconnect();
?>
<form id="updateFrom" action="update2.php" method="POST">
<table border="1" cellpadding="10">
<tr align='center'>
<td>Name</th>
<td><input name="name" type="text" value="<?php echo $name;?>"/></td>
</tr>
<tr align='center'>
<td>Quantity</th>
<td><input name="quantity" type="text" value="<?php echo $quantity;?>"/></td>
</tr>
<tr align='center'>
<?php $cat = $pdo->query("SELECT c_name, CATEGORY_ID FROM product_category");
?>
//Here the user selects the new category from the dropdown list
<td>Category</th>
<td>
<select name="c_id">
<?php
while ($rows = $cat->fetch(PDO::FETCH_ASSOC))
{
$cat_name = $rows['c_name'];
$cat_id = $rows['CATEGORY_ID'];
echo"<option value='$cat_id'>$cat_name</option>";
}
?>
</select>
</td>
</tr>
</table>
<input type="hidden" id="productId" name="productId" value="<?php echo $id;?>"/>
<button type="submit">update</button>
</form>
</body>
The code which makes the update (update2.php):
<?php
require 'database.php';
$id = null;
if ( !empty($_POST)) {
$id = $_POST['productId'];
$name = $_POST['name'];
$quantity = $_POST['quantity'];
// update data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE product set name = ?, quantity = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$quantity,$id));
Database::disconnect();
header("Location: index.php");
}
?>

You need to set the c_id column from $_POST['c_id'].
if ( !empty($_POST)) {
$id = $_POST['productId'];
$name = $_POST['name'];
$quantity = $_POST['quantity'];
$category = $_POST['c_id'];
// update data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE product set name = ?, quantity = ?, c_id = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$quantity,$category,$id));
Database::disconnect();
header("Location: index.php");
}
I also suggest that you have the existing category selected by default in the dropdown.
while ($rows = $cat->fetch(PDO::FETCH_ASSOC))
{
$cat_name = $rows['c_name'];
$cat_id = $rows['CATEGORY_ID'];
$selected = $cat_id == $data['c_id'] ? "selected" : "";
echo "<option value='$cat_id' $selected>$cat_name</option>";
}

Related

Getting last value from multidimensional array outside foreach loop

So I'm updating a database table and I receive a array from the input because there are multiple values (id[] , price[] , product[] , description[] and so on) but I want to get the LAST value of price[] outside foreach loop
I use this foreach loop that works to update the MAIN db table
foreach ($_POST['id'] as $key => $id) {
$array1 = $_POST['product'][$key];
$array2 = $_POST['priceunit'][$key];
$array3 = $_POST['quantity'][$key];
$array4 = $_POST['sum'][$key];
$array5 = $_POST['totalprice'][$key];
$query = $link -> prepare("UPDATE table SET product = ?, priceunit = ?, quantity = ?, sum = ?, totalprice = ? WHERE id = ?");
$query -> bind_param('sddddi',$array1,$array2,$array3,$array4,$array5,$id);
$result = $query-> execute();
$query -> close();
}
and now I want to get the LAST VALUE from $array5 so I can do this outside the loop
$sql = $link -> prepare("UPDATE table2 SET price = ? WHERE id = ?;");
$sql -> bind_param("ds",
$total, <- array5 last value
$_GET['id']);
$query = $sql -> execute();
$sql -> close();
this is the input
<tbody>
<?php
$sql = $link -> prepare("SELECT * FROM table WHERE id_proposta = ?;");
$sql -> bind_param('s',
$_GET['id']);
$sql -> execute();
$result = $sql -> get_result();
for ($i = 0; $r = $result -> fetch_assoc(); $i++){ ?>
<tr>
<input type="hidden" value="<?php echo $r['id']; ?>" name="id[]">
<td><textarea class="form-control" name="product[]" rows="3" id="textareaAutosize" data-plugin-textarea-autosize><?php echo $r['product']; ?></textarea></td>
<td><input type="text" class="priceunit" value="<?php echo $r['priceunit']; ?>" name="priceunit[]"></td>
<td><input type="text" class="qtd" value="<?php echo $r['quantity']; ?>" name="quantity[]"></td>
<td><input type="text" class="sum" value="<?php echo $r['sum']; ?>" name="sum[]" readonly></td>
<td><input type="text" class="totalprice" value="<?php echo $r['totalprice']; ?>" name="totalprice[]" readonly></td>
</tr>
<?php } $sql -> close(); ?>
</tbody>
Thanks.
Since you do this in the loop:
$array5 = $_POST['totalprice'][$key];
Then after the loop is finished, $array5 will be the last $_POST['totalprice']. So just use it:
$sql->bind_param("ds",
$array5,
$_GET['id']);
Or even this if you don't use all those temporary variables:
$sql->bind_param("ds",
$_POST['totalprice'][$key],
$_GET['id']);

Cannot loop through for each

I have a form in which a user can update a recipe. If the recipe they wish to edit is a recipe that comes default with the system, a new recipe is created with the additions and the copy of the original recipe is removed from their cookbook.
If the recipe they are updating is a recipe personal to them, a simple update query is to be conducted.
I can work out the logic for this but for both instances, I cannot loop through the ingredients and quantity array to update. Saving it displays as empty. I'm not sure if there is a problem with the form or the for each loops.
Snippets of code from the form include:
<form enctype="multipart/form-data" action="editDisplay.php" method="POST"
enctype="multipart/form-data">
<thead>
<div>
<tr>
<th>
Ingredient
</th>
<th>
Quantity
</th>
</tr>
</thead>
<tbody>
<?php
while ($dbRow2 = $dbQuery3->fetch(PDO::FETCH_ASSOC)) {
$ingredients=$dbRow2["ingredient"];
$quantity=$dbRow2["quantity"];
$id=$dbRow2["id"];
echo '<tr>';
echo '<td>';
?><input type="text" name="quantity[]" value="<?php echo $quantity?>">
<input type="hidden" name="ingredId[]" value="<?php echo $id?>">
<?php
echo '</td>';
echo '<td>';
?><input type="text" name="ingredients[]" value="<?php echo $ingredients
?>">
<?php
echo '</td>';
}
?>
</tbody>
<input class="btn btn-light btn-xl sr-button" name="submit" type="submit" value="Save changes">
</form>
On submission:
if(isset($_POST['submit'])){
$recipeID=$_POST['id'];
$name = $_POST['name'];
$description = $_POST['description'];
$method = $_POST['method'];
$duration = $_POST['duration'];
$difficulty = $_POST['difficulty'];
$source = $_POST['source'];
$ingredients = $_POST['ingredients'];
$quantity = $_POST['quantity'];
$id = $_POST['ingredId'];
$comment = $_POST['comment'];
$date = $_POST['date'];
$image = $_POST['image'];
$defaultRecipe = $_POST['defaultRecipe'];
$timestamp = date("Y/m/d");
$userRate = '1';
if($name !='' && $description !='' && $method !='' && $duration !='' && $difficulty !=''){
if ($defaultRecipe == 0){
$query1 = $db->prepare("update recipe set name=:name, description=:description, method=:method, duration=:duration, difficulty=:difficulty, source=:source where id=:id");
$dbParams1 = array('name'=>$name, 'description'=>$description, 'method'=>$method, 'duration'=>$duration, 'difficulty'=>$difficulty, 'source'=>$source, 'id'=>$recipeID);
$query1->execute($dbParams1);
foreach($ingredients as $ingredients){
//$ingredient = $value;
//print_r(array_values($ingredients));
//echo '<br>';
//echo $value;
foreach ($quantity as $quantity){
echo $quantity;
foreach ($id as $value){
echo $value;
echo $id;
print_r($value);
$query2 = $db->prepare("update ingredients set ingredient=:ingredients, quantity=:quantity where id=:id");
$dbParams2 = array('ingredients'=>$ingredients, 'quantity'=>$quantity, 'id'=>$value);
$query2->execute($dbParams2);
}
}
}
$query4 = $db->prepare("update user_cookbook set comment=:comment, commentDate='$timestamp' where recipeID=:recipeID and userID=:userID");
$dbParams4 = array('comment'=>$comment, 'recipeID'=>$recipeID, 'userID'=>$thisUser);
$query4->execute($dbParams4);
}
else {
$default = 0;
$query10 = $db->prepare("INSERT INTO recipe values (NULL, :name, :description, :method, :duration, :difficulty, :source, :userRate, :defaultRecipe)");
$dbParams10 = array('name'=>$name, 'description'=>$description, 'method'=>$method, 'duration'=>$duration, 'difficulty'=>$difficulty, 'source'=>$source, 'userRate'=>$userRate, 'defaultRecipe'=>$default);
$query10->execute($dbParams10);
$recipeID1 = $db->lastInsertId();
$query400 = $db->prepare("INSERT INTO user_cookbook values (NULL, :userID, :recipeID, :comment, '$timestamp')");
$dbParams400 = array('userID'=>$thisUser, 'recipeID'=>$recipeID1, 'comment'=>$comment);
$query400->execute($dbParams400);
foreach($ingredients as $ingredient){
foreach ($quantity as $quantities){
$query2 = $db->prepare("INSERT INTO ingredients values (NULL, :ingredients, :quantity)");
$dbParams2 = array('ingredients'=>$ingredient, 'quantity'=>$quantities);
$query2->execute($dbParams2);
$ingredientID = $db->lastInsertId();
$query3 = $db->prepare("INSERT INTO recipe_ingredients values (NULL, :recipeID, :ingredientID)");
$dbParams3 = array('recipeID'=>$recipeID, 'ingredientID'=>$ingredientID);
$query3->execute($dbParams3);
}
}
$query500 = $db->prepare("delete from user_cookbook where recipeID=:recipeID and userID=:userID");
$dbParams500 = array('recipeID'=>$recipeID, 'userID' =>$thisUser);
$query500->execute($dbParams500);
}
}
}
?>

Database won't stay updated after switching script

I'm trying to update this database, and I've verified within this script that the update is completed, and that the $nw and $p variables are correct.
<?php
session_start();
$num = (int) $_SESSION["cart"];
$cart = $num + 1;
$_SESSION["cart"] = (string) $cart;
$nme = $_POST['nameofitem'];
$pst = $_SESSION["user"];
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
$query = "select * from Items where Items.Id = '$nme'";
$result = $db->query($query) or die ($db->error);
$item = $result->fetch_array();
$nw = $item[5] - 1;
$p = (int) $pst;
echo $p;
$query3 = "update Items set Quantity = '$nw' where Id = '$p'";
$db->query($query3) or die ("Invalid insert " . $db->error);
$query2 = "insert into Bought (Name, Cost, BuyerID) values ('$item[1]', '$item[4]', '$pst')";
$db->query($query2) or die ("Invalid insert " . $db->error);
header("Location: store.php");
?>
However, when it redirects to this script, it echoes the information as if it weren't updated. What is the problem?
<?php
session_start();
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
$user = $_SESSION["user"];
$pw = $_SESSION["pw"];
# determines number of items in cart to display
if (!isset($_SESSION["category"]))
$_SESSION["category"] = "Book";
if (isset($_POST["Ccategory"])) {
$cat = $_POST["Ccategory"];
$_SESSION["category"] = $cat;
}
if (!isset($_SESSION["cart"]))
$_SESSION["cart"] = "0";
$cart = $_SESSION["cart"];
?>
<!DOCTYPE html>
<html>
<?php # setting up table with items to buy ?>
<table border = "1" border-spacing = "5px" >
<caption><h2> UVA Bookstore 2.0</h2>
<p align=right> Items in cart: <?php echo $cart?> </p> <br />
<b><i>Welcome to the new and improved bookstore with a better selection than ever</i></b>
<br/><br/>
</caption>
<tr align = "center">
<th>Item</th>
<th>Description</th>
<th>Price</th>
<th>Number left</th>
<th>Buy</th>
</tr>
<?php
$category = $_SESSION["category"];
$query = "select * from Items where Items.Category = '$category'";
$result = $db->query($query) or die ($db->error);
$rows = $result->num_rows;
for ($i = 0; $i < $rows; $i++)
{
$row = $result->fetch_array();
?>
<form action="addtocart.php"
method="POST">
<tr align = "center">
<td>
<?php
echo $row[1];
?>
</td>
<td> <?php echo $row[3];?> </td>
<td> <?php echo $row[4];?> </td>
<td> <?php echo $row[5];?> </td>
<?php # sets up add to cart button that adds item to cart ?>
<td> <input type = "hidden" name ='nameofitem'
value= "<?php echo $row[0]?>">
<input type='submit' value='Add to Cart'> </input> </td>
</tr>
</form>
<?php
}
# form to check out and go to summary page ?>
<form action = "store.php"
method = "POST">
<tr align = "center"> <td>
<select name = "Ccategory">
<option value = "Book">Books</option>
<option value = "Music">Music</option>
<option value = "Car">Cars</option>
</select>
<input type = "hidden" name = "cat"> </td>
<td> <input type = "submit" value = "Switch Category"> </td>
</form>
<form action="summary.php"
method="POST">
<td> <input type = "submit" value = "Check out"> </td> </tr>
</table><br/>
</form>
</html>
Have you tried changing
$query3 = "update Items set Quantity = '$nw' where Id = '$p'";
to
$query3 = "update Items set Quantity = '$nw' where Id = $p";
The best way to determine if an UPDATE should work is to replace it with a SELECT containing the same WHERE clause. This way you can see what rows would be changed if you were to run the original query.
Otherwise, it seems to be the case that your changes in the current transaction are never committed. Is this the only script that has an issue with updates to the database? Please see the PHP manual for more information:
//mysqli::commit -- mysqli_commit — Commits the current transaction
bool mysqli::commit ([ int $flags [, string $name ]] )
A commit should be issued when you are done doing all updates that have dependencies (or for those that are atomic), however, you don't always have to commit depending on the configuration of your server. Also, it looks like your script has SQL injection vulnerabilities as other have mentioned. It would probably be best to use prepared statements or sanitize your inputs.

Update and insert category and moderator

I have file category.php where i have:
Category name / Moderator
Economy / uername1
Math / username2
Biology / username1
Every category i can update and add new category with username who can moderate some category.
I have problem with categorie.php because when i click update on label Category name in input write me Economy and username1 when i click on update some other category like Math in input writes me again Economy and username1.
Second problem i have is when i want to add a new category with moderator. After i click submit doesn't insert in my mysql database name of added category with moderator.
<?PHP
session_start();
if(!isset($_SESSION["type_id"])){
header("Location:index.php");
exit();
}
else if($_SESSION["type_id"]!=0)
{
header("Location:index.php");
exit();
}
include_once("meni.php"); ?>
<div class="mid-right"><?php
$dbc=mysql_connect("localhost","2013","013");
if (!$dbc)
{
echo 'Error!'.mysql_error();
exit();}
$db=mysql_select_db("2013_db",$dbc);
$category = $category_id = $name = $user_id = "";
$id = 0;
if(isset($_POST['username'])) {
if (isset($_POST['type_id'])) {
$type_id = $_POST['type_id'];
} else {
$type_id = 2;
}
$id = $_POST['new'];
if ($id == 0) {
$name = $_POST['name'];
$user_id = $_POST['user_id'];
$category_id = $_POST['category_id'];
$sql = "INSERT INTO category (category_id, name, user_id) VALUES ($category_id, '$name', '$user_id');";
}
$result=mysql_query($sql);
mysql_close($db);
header("Location: category.php");
}
if(isset($_POST['category_id']) && isset($_POST['name']) && isset($_POST['moderator']) && $_SESSION['type_id'] == 0) {
$name = $_POST['name'];
$user_id = $_POST['moderator'];
$category_id = $_POST['category_id'];
$sql = "UPDATE category SET name = '$name', user_id = $user_id WHERE category_id = $category_id";
$result=mysql_query($sql);
mysql_close($db);
header("Location: category.php");
}
if(isset($_GET['categories'])) {
$kategorija_id = $_GET['categories'];
if ($id==2) {
$id = $_SESSION["category_id"];
}
$dbc=mysql_connect("localhost","2013","2013");
if (!$dbc)
{
echo 'Error!'.mysql_error();
exit();}
$db=mysql_select_db("2013_db",$dbc);
$sql = "SELECT k.category_id, k.name, ko.username FROM category k, user ko WHERE k.user_id = ko.user_id AND ko.type_id = 1";
$result=mysql_query($sql);
list($category_id, $name, $user_id) = mysql_fetch_array($result);
} else {
$name = "";
}
?>
<form method="POST" action="categorie.php">
<div>
<input type="hidden" name="category_id" value="<?php echo $category_id ?>"/>
<input type="hidden" name="new" value="<?php echo $id?>"/>
<table>
<tr>
<td><label for="name">Category name:</label></td>
<td><input type="text" name="name" id="name" value="<?php echo $name ?>"/></td>
</tr>
<tr>
<td><label for="moderator">Moderator:</label></td>
<td><select name="moderator">
<?php
$sql2 = "SELECT user_id, username FROM user WHERE type_id = 1 ";
$rs2 = mysql_query($sql2);
while(list($user_id, $username) = mysql_fetch_array($rs2)){
?>
<option value="<?php echo $user_id ?>"><?php echo $username ?></option><?php } ?>
</select></td>
<tr>
<tr>
<td colspan="2"><input type="submit" value="Send" id="submit"/></td>
</tr>
</table>
</div>
</form>
<?php
mysql_close($dbc);
?>
</div>
</div><?php include("footer.php"); ?>
</body>
</html>

Update mysql record and pass id

My form is:
<form class="form-horizontal" action="update.php?id=<?php echo $id ?>" method="post">
$sql = 'SELECT * FROM prekes WHERE pirkejo_id=' . $pirkejas . '';
$q = $pdo->prepare($sql);
$prekes = array();
foreach ($pdo->query($sql) as $row) {
if ($row['prek_pav'] != '') {
array_push($prekes, $row);
}
}?>
<input name="prekes[1][pavadinimas]" type="text" value="<?php echo $prekes[0]['prek_pav']?>">
<input name="prekes[1][kaina]" type="text" value="<?php echo $prekes[0]['prek_kaina'] ?>">
<input name="prekes[2][pavadinimas]" type="text"value="<?php echo $prekes[1]['prek_pav']?>">
<input name="prekes[2][kaina]" type="text" value="<?php echo $prekes[1]['prek_kaina'] ?>">
I dont know how to optimize it. I want to update my records in database and have no idea how to pass prekes_id value to UPDATE sql.
I found that My update updates all records with the last value from my form. all recors are same as last entered.
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE customers set name = ?, pavarde = ?, ak = ?, numeris = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name, $pavarde, $ak, $numeris, $id));
foreach ($prekes as $preke) {
$sql = "UPDATE prekes SET prek_pav= ?,prek_kaina=? WHERE prekes_id=".$preke['prekes_id'];
$q = $pdo->prepare($sql);
$q->execute(array($preke['pavadinimas'], $preke['kaina']));
}
Database::disconnect();
header("Location: default.php");
I use this code to solve this. Are there any better working solution to this problem?
My table prekes (prekes_id, pirkejo_id, prek_pav, prek_kaina). I take pirkejo_id from $_POST['id'].

Categories