PHP displaying updated values - php

the quantity is an array of items
<td>
<input type="text" size="4" name="qty[<?php echo $pro_id;?>]"style="text-
align:center" value="<?php echo $_SESSION['qty']; ?>">
</td>
<?php
the update function works perfectly
if(isset($_POST['update'])) {
$ip=getIp();
$sql = "UPDATE cart SET qty=? where p_id=? and ip_add=?";
$stmt = mysqli_prepare($con, $sql);
foreach ($_POST['qty'] as $pro_id=>$qty) {
$stmt->bind_param("iis", $qty, $pro_id, $ip);
$stmt->execute();
}
}
this is what i used to display the new quantity, but the values are displayed in the incorrect product field
$sql = $con->query("select * from cart where p_id='$pro_id'");
$row=$sql->fetch_array(MYSQLI_BOTH);
$_SESSION['qty']=$row['qty'];
?>
the button which updates the cart
<td><input type="submit" name="update" value="Update quantity"></td>
<td><button style="height:20px;width:128px">
Continue Shopping</button></td>
<td><button>Checkout</button>
</td>
</table>

When the quantity is a array and the data in the database is correct you need the SESSION qty as a Array!
Try this:
$sql = $con->query("select * from cart where p_id='$pro_id'");
$row=$sql->fetch_array(MYSQLI_BOTH);
$_SESSION[$pro_id]['qty']=$row['qty'];
and this
<td>
<input type="text" size="4" name="qty[<?php echo $pro_id;?>]"style="text-
align:center" value="<?php echo $_SESSION[$pro_id]['qty']; ?>">
</td>
<?php

Related

Updating a field from an sql table from php

I have a table with more columns. On one column I have 3 buttons for each row with different queries associated. When I click one of the buttons, field in the table from my database should update.The problem is that when I click on a button on any row in the table, it updates only the field from the first row.For example, I have a table with 10 rows.If I click one of the buttons on the 10th row IT will update my first row, not the 10th one as I want. Is there any possibility to solve this?
This is the code..I'm sorry it is too long:
<?php
$query = "SELECT * FROM masculin ORDER BY id_concurent";
$result = mysqli_query($link ,$query);
$row = mysqli_fetch_assoc($result);
if(isset($_POST['locul1']))
{
$sql = "UPDATE masculin SET Premiu=1 WHERE CNP='".$row['CNP']."'";
mysqli_query($link,$sql);
header("Location:administrare.php");
}
else if(isset($_POST['locul2']))
{
$sql = "UPDATE masculin SET Premiu=2 WHERE CNP='".$row['CNP']."'";
mysqli_query($link,$sql);
header("Location:administrare.php");
}
else if(isset($_POST['locul3']))
{
$sql = "UPDATE masculin SET Premiu=3 WHERE CNP='".$row['CNP']."'";
mysqli_query($link,$sql);
header("Location:administrare.php");
} ?>
<u><i><h1 align="center">Administrare concurenti</h1></i></u>
<u><i><h2>MASCULIN</h2></i></u>
<?php
$query = "SELECT * FROM masculin ORDER BY id_concurent";
$result = mysqli_query($link ,$query);
if (mysqli_num_rows($result) == 0) {
echo 'Inca nu s-a inscris niciun concurent.';
} else {
?>
<table width="100%">
<tr>
<th>Nr.<br />concurs</th>
<th>Nume</th>
<th>Prenume</th>
<th>CNP</th>
<th>Categoria</th>
<th>Varsta</th>
<th>Premiu</th>
<th>Modifica<br />rezultat</th>
<th>Descalifica</th>
</tr>
<?php while($row = mysqli_fetch_assoc($result)){ ?>
<tr>
<?php
$query1="SELECT id_concurent FROM concurenti WHERE CNP='".$row['CNP']."'";
$result1=mysqli_query($link,$query1);
$nr_conc=mysqli_fetch_assoc($result1);
?>
<td> <?php echo $nr_conc['id_concurent'] ?> </td>
<td> <?php echo $row['Nume'] ?> </td>
<td> <?php echo $row['Prenume'] ?> </td>
<td> <?php echo $row['CNP'] ?> </td>
<td> <?php echo $row['Categorie'] ?> </td>
<td> <?php echo $row['Varsta'] ?> </td>
<td> <?php echo $row['Premiu'] ?> </td>
<td>
<form action="administrare.php" method="post">
<input type="submit" name="locul1" value="Premiul 1">
<input type="submit" name="locul2" value="Premiul 2">
<input type="submit" name="locul3" value="Premiul 3">
</form>
</td>
</tr>
<?php } ?>
</table> <?php } ?>
for updated the da tbale row when you submit the values related to a html table row you should add and hidden input with the value that let you reach the correct row eg:
<form action="administrare.php" method="post">
<input type="submit" name="locul1" value="Premiul 1">
<input type="submit" name="locul2" value="Premiul 2">
<input type="submit" name="locul3" value="Premiul 3">
<input type="hidden" name="CNP" value="<?php echo $row['CNP'] ?>">
</form>
and in your sql updated query add the POST value related to the row
$sql = "UPDATE masculin SET Premiu=1 WHERE CNP='".$_POST['CNP']. "'";

How to get ID on a specific row in PHP and MySQL

PHP is giving me error of
Notice: Undefined index: product_id in C:\xampp\htdocs\odieinventory\admin\add_sales.php on line 6
This is my query
<?php
if (isset($_POST['addCart'])) {
$product_id = $_POST['product_id'];
$qtyBuy = $_POST['qtyBuy'];
$addQuery = "INSERT INTO sales (product_id, quantity) VALUES ($product_id, $qtyBuy)";
$execQuery = mysqli_query($connection, $addQuery);
}
?>
This is my table
<form action="add_sales.php" method="POST">
<?php
$query = "SELECT * FROM products";
$exec = mysqli_query($connection, $query);
while ($row = mysqli_fetch_array($exec)) {
$product_id = $row['product_id'];
$product_name = $row['product_name'];
$description = $row['description'];
$product_quantity = $row['quantity'];
$product_price = $row['sell_price'];
?>
<tr>
<td class="text-center"><?php echo $product_id; ?>
<input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
</td>
<td><?php echo $product_name; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $product_price; ?></td>
<td><?php echo $product_quantity; ?></td>
<td><input type="number" min="1" max="999" name="qtyBuy"></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="form-group">
<input type="submit" name="addCart" value="Add Items to Cart" class="btn btn-info pull-right">
</div>
</div>
</form>
I would also like to ask for advice on how to insert records on my cart. By clicking 'Add Items to Cart', I like to pass ONLY the items with values on the quantitiy input on the cart. How to achieve this with PHP?
In your table file table.php , you have to:
1- open the table and tbody HTML tags
2- make your html attributes form name as array (you have more than one input with the same name), in your case you are only submiting the last product_id and the last qtyBuy input values.
table.php
<form action="add_sales.php" method="POST">
<div><table><tbody>
<?php
$query = "SELECT * FROM products";
$exec = mysqli_query($connection, $query);
while ($row = mysqli_fetch_array($exec)) {
$product_id = $row['product_id'];
$product_name = $row['product_name'];
$description = $row['description'];
$product_quantity = $row['quantity'];
$product_price = $row['sell_price'];
?>
<tr>
<td class="text-center"><?php echo $product_id; ?>
<input type="hidden" name="product_id[]" value="<?php echo $product_id; ?>">
</td>
<td><?php echo $product_name; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $product_price; ?></td>
<td><?php echo $product_quantity; ?></td>
<td><input type="number" min="1" max="999" name="qtyBuy[]"></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="form-group">
<input type="submit" name="addCart" value="Add Items to Cart" class="btn btn-info pull-right">
</div>
</form>
In your add_sales.php file, you have to loop the $_POST['qtyBuy'] variable and check if the given quantity of each product is > 0
add_sales.php
<?php
if (isset($_POST['addCart']) && $_POST['addCart']=="Add Items to Cart") {
foreach($_POST['qtyBuy'] as $index=>$value){
if($value > 0){
$addQuery = "INSERT INTO sales (product_id, quantity) VALUES (".$_POST['product_id'][$index].", ".$value.")";
$execQuery = mysqli_query($connection, $addQuery);
}
}
}
?>
First of all, you should never put users input ($_POST) directly into the SQL to avoid SQL injection - use prepared statements with mysqli.
It would be easiest for you to add a separate form with product ID and quantity field and an "Add to cart" button for each product in the table.

Button to delete row from table - PHP SQL

I have a web page that outputs data from my sql database. Each row has a delete button that should delete the data in this particular row. I am having a issue where when I click the delete button it always deletes the row with the first/lowest ID regardless of which button I click. It doesnt delete the row I want it to delete. Here is my code:
HTML
<form action="process.php" method="post">
<?php
$sql = "
SELECT *
FROM playerTeam
";
$result = mysqli_query($connection, $sql);
?>
<table>
<?php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><input type="text" name="id" value="<?php echo $row['id']?>"></td>
<td><input type="text" name="fName[]" value="<?php echo $row['firstName']?>"></td>
<td><input type="text" name="sName[]" value="<?php echo $row['surName']?>"></td>
<td><input type="text" name="team[]" value="<?php echo $row['team']?>"></td>
<td><input type="submit" name="delete" value="Delete"></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
<?php
}
}
?>
</table>
</form>
process.php
if (isset($_POST['delete'])) {
$id = $_POST['id'];
$sql = "DELETE FROM playerTeam WHERE id='$id'";
if (mysqli_query($connection, $sql)) {
echo "Record deleted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
please could someone help me. Thanks
Because you delete the value of last id in
$id = $_POST['id'];
$sql = "DELETE FROM playerTeam WHERE id='$id'";
the value of $_POST['id'] is equal to last row in <?php echo $row['id']?>
in each run of the while the $_POST['id'] value replaced by new $row['id'] so the last on would be read in $_POST['id']
As you are using while($row = mysqli_fetch_assoc($result)), this will loop to the last row in your MySQL Table, thus every time, it will have the last id of your table.
You can code it in a way that your delete script will get the id. So, your delete button for each row will be have the row id, e.g. process.php?1, process.php?2, process.php?3 and so on.
tablepage.php (not sure of your page's real name)
Replace this line:
<td><input type="submit" name="delete" value="Delete"></td>
With this:
<td><p><a href="/process.php?id=<?php echo $id; ?>"></td>
process.php?id=1
// this will get `id=1` and thus your `id` will be `1`, and it will delete row `1`.
$id = $_GET['id'];
$sql = "DELETE FROM playerTeam WHERE id='$id'";
if (mysqli_query($connection, $sql)) {
echo "Record deleted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
Hope that helps, thanks!
In actual in this condition ,use ajax and jquery is much more easier i think .But do only by php gonna be use logic code
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td><input type="text" name="id_<?= $i ?>" value="<?php echo $row['id']?>"></td>
<td><input type="text" name="fName[]" value="<?php echo $row['firstName']?>"></td>
<td><input type="text" name="sName[]" value="<?php echo $row['surName']?>"></td>
<td><input type="text" name="team[]" value="<?php echo $row['team']?>"></td>
<td><input type="submit" name="delete[<?= $i ?>]" value="Delete"></td>
<td><input type="submit" name="update[<?= $i ?>]" value="Update"></td>
</tr>
<?php
$i++; //for unique num for each row
}
process.php
if (isset($_POST['delete'])){
$delete_id = array_keys($_POST['delete']);//print array key as a array
$delete_id = $delete_id[0];//so get array key
$id = $_POST["id_$delete_id"];//get its relative id
.....
}

PHP delete/update only affects last MySQL row

Whether using the delete or update function, only the last row is updated/deleted. It doesn't matter what field I update/delete, only the last row is passed. I'm unable to find the issue other than the fact that a unique ID is not being passed. I'm new to PDO, so I'm not too familiar with debugging. Any help is appreciated.
<form action="" id="form" method="post">
<?php
function UserForm($customers = array())
{
ob_start(); ?>
<?php
$id = $customers['id'];
?>
<tr>
<td><input type="text" name="name" value="<?php echo $customers['name']; ?>"></td>
<td><input type="text" id="email" name="email" value="<?php echo $customers['email']; ?>"></td>
<td><input type="text" id="phone" name="phone" value="<?php echo $customers['phone']; ?>"></td>
<td><input type="text" id="address" name="address" value="<?php echo $customers['address']; ?>"></td>
<td><input type="text" id="proudct" name="product" value="<?php echo $customers['product']; ?>"></td>
<td><input type="text" id="firmware" name="firmware" value="<?php echo $customers['firmware']; ?>"></td>
<td><input type="text" id="datepicker" class="datepicker" name="purchase_date" value="<?php echo $customers['purchase_date']; ?>"></td>
<td align="center">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="submit" value="<?php echo $id; ?>" name="delete" value="X" onclick="return confirm('WARNING! \n\nAre you sure you want to DELETE?')" >
</td>
</tr>
<tr>
<td colspan="8">
<input type="hidden" name="id_update" value="<?php echo $id; ?>" />
<input type="submit" name="update" value="Update <?php echo $id; ?>" />
</td>
</tr>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
} ?>
<?php
$pdo = new PDO("mysql:host=localhost;dbname=project", $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
//$query = $pdo->prepare("SELECT * FROM customers ORDER BY purchase_date ASC");
if (isset($_POST['desc'])){
$sort = "desc";
$query = $pdo->prepare("SELECT * FROM customers ORDER BY purchase_date DESC");
}
else {
$sort = "asc";
$query = $pdo->prepare("SELECT * FROM customers ORDER BY purchase_date ASC");
}
$query->execute();
?>
<table class="table table-striped table-bordered table-responsive">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Address</th>
<th>Product</th>
<th>Firmware Version</th>
<th align="center">
Purchase Date
<?php
if ($sort == "asc") {
echo '<input type="hidden" value="Desc" name="desc" id="sort">';
echo '<a name="desc" href="javascript: submitform()">Desc</a>';
}
else {
echo '<input type="hidden" value="Asc" name="asc" id="sort">';
echo '<a name="asc" href="javascript: submitform()">Asc</a>';
}
?>
</th>
<th>Delete</th>
</tr>
</thead>
<?php
while($customers = $query->fetch(PDO::FETCH_ASSOC)){
echo UserForm($customers);
} //end of while
// Delete customer
if(isset($_POST['delete'])) {
try{
$id = $_POST['id'];
$query = $pdo->prepare("delete from customers where id = :id");
$query->bindParam(':id', $id);
$query->execute(array(':id' => $id));
echo "Customer successfully deleted." . $_POST['id'];
echo '<META http-equiv="refresh" content="1;URL=view_edit.php">';
}catch(PDOException $e){
echo "Failed to delete the MySQL database table ... :".$e->getMessage();
} //end of try
} //end of isset delete
// Edit customer
if(isset($_POST['update'])) {
try {
$name = $_POST['name'];
$id = $_POST['id'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$product = $_POST['product'];
$firmware = $_POST['firmware'];
$purchase_date = $_POST['purchase_date'];
$query = $pdo->prepare("UPDATE customers SET name = '$name', email = '$email', phone = '$phone', address = '$address', product = '$product', firmware = '$firmware', purchase_date = '$purchase_date' where id = '$id'");
$query -> execute( array(
':name' => $name,
':email' => $email,
':phone' => $phone,
':address' => $address,
':product' => $product,
':firmware' => $firmware,
':purchase_date' => $purchase_date
));
echo "Customer succesfully updated" . $id;
echo '<META http-equiv="refresh" content="1;URL=view_edit.php">';
}catch(PDOException $e){
echo "Error! Failed to update customers :".$e->getMessage();
}//end of try
} //end of isset update
?>
To debug your code, try using print_r($_POST); exit(); immediately after your if(isset($_POST['delete/update'])) { to see what's being passed in the array when you post.
I'm a bit of a noob myself, but I suspect the problem here could be you haven't defined where your form starts and ends, so you're submitting the whole table. Try adding a form for each of your records, with a form name the same as your customer id.
<form name="formname<?php echo $id; ?>"> ... your input fields and submit button... </form>, then when you submit, you'll only be submitting that particular form and the data it contains.
I hope that helps!
$query = $pdo->prepare("delete from customers where id = :id"
I bet this ID is unique..
Resolved the issue. Moved the <form> tag above the beginning of the table row.

Update cart - mysql table update - while loop

new guy here!
I am building a custom shopping cart driven by mysql and i am trying to update my cart item by item in terms of quantity. It seems that i am doing something wrong because when i try to update the quantity it only update the last item. I am posting the code below. Any help would be appreciated. Thanks in advance.
1.cart.php:
$sql = "select * from orders";
$result = mysql_query($sql);
$num = mysql_num_rows($result);
echo "Στοιχεία: ".$num;
?>
<form name="cart" method="post" action="updatecart.php">
<table border="2">
<tr>
<td>Α/Α</td>
<td>img_name</td>
<td>Reprints</td>
<td>Color</td>
</tr>
<?php
if($num){
while ($row = mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $row['item_id']; ?></td>
<td><?php echo $row['img_name']; ?></td>
<td><input type="number" name="quantity" value="<?php echo $row['quantity']; ?>"></td>
<input type="hidden" name="item_id" value="<? echo $row['item_id']; ?>">
<td><?php echo $row['color']; ?></td>
</tr>
<?php
}
}
?>
</table>
<input type="submit" name="update" value="Update Cart" />
<input type="button" name="2checkout" value="Proceed to Checkout" />
</form>
2.updatecart.php
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<?php
$database_name = "vog";
$conn = mysql_connect("localhost","root","toor");
mysql_select_db($database_name);
$num = 2; //na to ferw me session meta edw!
if(isset($_POST['update'])){
$item_id = $_POST['item_id'];
$i=1;
while($i<=$num){
$item_id = $_POST['item_id'][$i];
$quantity = $_POST['quantity'];
$sql2 = "update orders SET quantity = '$quantity' where item_id = '$item_id' ";
$result2 = mysql_query($sql2) or die ("Error in query: $result2");
$i++;
}
}
if(isset($result2)){
header("Location:cart.php");
}
?>
So far it updates just the last record.
Your problem is with the names of the fields in your HTML form:
<input type="number" name="quantity" value="<?php echo $row['quantity']; ?>">
<input type="hidden" name="item_id" value="<? echo $row['item_id']; ?>">
I think you meant to call them quantity[] and item_id[] instead, so they will and up as arrays in your $_POST variable later on, now they overwrite eachother, making $_POST['item_id'] only contain the last id in the database.
in #1.cart.php use the inputs as array:
<input type="number" name="quantity[<?php echo $row['item_id']; ?>]" value="<?php echo $row['quantity']; ?>">
<input type="hidden" name="item_id[<?php echo $row['item_id']; ?>]" value="<? echo $row['item_id']; ?>">
and in #2.updatecart.php: process it like
foreach($_POST['item_id'] as $key => $id){
$item_id = $id;
$quantity = $_POST['quantity'][$key];
$sql2 = "update orders SET quantity = '$quantity' where item_id = '$item_id' ";
$result2 = mysql_query($sql2) or die ("Error in query: $result2");
$i++;
}
You need to tell PHP that you're using an array for your submitted form items. The way to do this is to make the name of each input quantity[]. You can also place the item ID directly in the array as a key. In cart.php you can do this in your loop:
<input type="number" name="quantity[<?php echo $row['item_id']; ?>]"
value="<?php echo $row['quantity']; ?>"/>
In effect, this will putput something like:
<input type="number" name="quantity[2]" value="1" />
<input type="number" name="quantity[4]" value="1" />
<input type="number" name="quantity[8]" value="2" />
i.e. 1 of item 2, 1 of item 4 and 2 of item 8.
Then, in updatecart.php you can read in the array and process it in a loop.
if(isset($_POST['update'])){
foreach ($_POST['quantity'] as $item_id => $item_qty) {
$item_id = (int)$item_id;
$item_qty = (int)$item_qty;
$sql2 = "update orders SET quantity = '$item_qty' where item_id = '$item_id' ";
mysql_query($sql2);
}
}

Categories