Getting last value from multidimensional array outside foreach loop - php

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']);

Related

SQL Update Query doesnt' Update when using Dropdown list

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>";
}

Form values not posting

I have two pages. The first one I am sending data over to the second page. The second page I am using to edit the data sent over and other data within my database. I call for the data I sent over like this:
$id = $_POST['id'];
$first = $_POST['first'];
$last = $_POST['last'];
$product = $_POST['product'];
The issue is I have other data on the page that and whenever I edit any of this information, I want to be able to do an UPDATE query to save the new information. However, my query isn't working and I believe it is because my new input field's (data I didn't send over from the first page) data is not being recognized.
Whenever I var_dump the values, I get the data (and in the same format) as how I sent it over to this page.
Here is my code for the second page:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$id = $_POST['id'];
$first = $_POST['first'];
$last = $_POST['last'];
$product = $_POST['product'];
$newId = filter_var($id, FILTER_SANITIZE_STRING);
try {
$host = 'localhost';
$name = '';
$user = '';
$password = '';
$dbc = new PDO("mysql:host=$host;dbname=$name", $user, $password);
}catch(PDOException $e) {
echo $e->getMessage();
}
$stmt = $dbc->query("SELECT * FROM users WHERE id='$newId' ");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
//print_r($stmt);
while($row = $stmt->fetch()) {
$productAmount = $row['amount'];
$productAvailable = $row['available'];
?>
<form name="update" method="POST">
<input type="text" name="id" value="<?php echo $newId; ?>">
<input type="text" name="first" value="<?php echo $first; ?>">
<input type="text" name="last" value="<?php echo $last; ?>">
<input type="text" name="product" value="<?php echo $product; ?>">
<input type="text" name="amount" value="<?php echo $row['amount']; ?>">
<input type="text" name="available" value="<?php echo $row['available']; ?>">
<button type="submit">Update Product Information</button>
</form>
<?php
}
var_dump($_POST);
if(isset($_POST['update'])) {
$stmt = $dbc->prepare("UPDATE users SET first = ?, last = ?, product = ?, amount = ?, available = ? WHERE id = ?");
$stmt->bindParam(1, $_POST['first']);
$stmt->bindParam(2, $_POST['last']);
$stmt->bindParam(3, $_POST['product']);
$stmt->bindParam(4, $productAmount);
$stmt->bindParam(5, $productAvailable);
$stmt->bindParam(6, $newId);
$stmt->execute();
}
?>
When I do var_dump($_POST); I get the following values, clearly not including the amount and available data.
array(5) { ["id"]=> string(1) "4" ["first"]=> string(3) "Tom" ["last"]=> string(5) "Brady" ["product"]=> string(3) "Tea" ["edit"]=> string(4) "Edit" }
Why isn't all my data being recognized?
Nowhere in your script do you have:
$productAmount = $_POST['amount'];
$productAvailable = $_POST['available'];
Add those 2 lines just below: $product = $_POST['product'];
UPDATED
Is the form supposed to be populated by the database? Or the form itself? If by the database (initially), then you'll need to change all the $variables in the form to their corresponding field names from the table, ie. $row['id'], $row['first'], etc.
See below for update...
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$id = $_POST['id'];
$first = $_POST['first'];
$last = $_POST['last'];
$product = $_POST['product'];
$productAmount = $_POST['amount'];
$productAvailable = $_POST['available'];
$newId = filter_var($id, FILTER_SANITIZE_STRING);
try {
$host = 'localhost';
$name = '';
$user = '';
$password = '';
$dbc = new PDO("mysql:host=$host;dbname=$name", $user, $password);
} catch(PDOException $e) {
echo $e->getMessage();
}
if (isset($_POST['update'])) {
$stmt = $dbc->prepare("UPDATE users SET first = ?, last = ?, product = ?, amount = ?, available = ? WHERE id = ?");
$stmt->bindParam(1, $_POST['first']);
$stmt->bindParam(2, $_POST['last']);
$stmt->bindParam(3, $_POST['product']);
$stmt->bindParam(4, $_POST['amount']);
$stmt->bindParam(5, $_POST['available']);
$stmt->bindParam(6, $newId);
$stmt->execute();
}
if ( !empty($newId) ) {
$stmt = $dbc->query("SELECT * FROM users WHERE id='$newId' ");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while( $row = $stmt->fetch() ) {
?>
<form action="" method="post">
<input type="text" name="id" value="<?php echo $row['id']; ?>">
<input type="text" name="first" value="<?php echo $row['first']; ?>">
<input type="text" name="last" value="<?php echo $row['last']; ?>">
<input type="text" name="product" value="<?php echo $row['product']; ?>">
<input type="text" name="amount" value="<?php echo $row['amount']; ?>">
<input type="text" name="available" value="<?php echo $row['available']; ?>">
<input type="submit" name="update" value="Update Product Information">
</form>
<?php
}
}
var_dump($_POST);
For the Undefined index just use a ternary in your form like so:
... value="<?php echo !empty($row['amount']) ? $row['amount'] : ''; ?>">
... value="<?php echo !empty($row['amount']) ? $row['available'] : ''; ?>">
Change these lines:
$stmt->bindParam(4, $productAmount);
$stmt->bindParam(5, $productAvailable);
to:
$stmt->bindParam(4, $_POST['amount']);
$stmt->bindParam(5, $_POST['available']);
So the result of cleaning up second part of your code would be this:
No need for a form name.
name="update" goes in the button's markup.
$_POST array now contains the new variables.
We check to make sure update is set before running the query.
<form method="POST">
<input type="text" name="id" value="<?php echo $newId; ?>">
<input type="text" name="first" value="<?php echo $first; ?>">
<input type="text" name="last" value="<?php echo $last; ?>">
<input type="text" name="product" value="<?php echo $product; ?>">
<input type="text" name="amount" value="<?php echo $row['amount']; ?>">
<input type="text" name="available" value="<?php echo $row['available']; ?>">
<button type="submit" name="update">Update Product Information</button>
</form>
<?php
}
if(isset($_POST['update'])) { // checking the button
$stmt = $dbc->prepare("UPDATE users SET first = ?, last = ?, product = ?, amount = ?, available = ? WHERE id = ?");
$stmt->bindParam(1, $_POST['first']);
$stmt->bindParam(2, $_POST['last']);
$stmt->bindParam(3, $_POST['product']);
$stmt->bindParam(4, $_POST['amount']); // now it is in the POST array
$stmt->bindParam(5, $_POST['available']); // same here
$stmt->bindParam(6, $newId);
$stmt->execute();
}

How to update multiple table row array in php mysql

it display the record but when I save it. it doesnt work. please have a check on my array query.
<form action="saveupdaterecord.php" class="form-horizontal" role="form" method="post">
<table>
<tr>
<?php
$result = $db->prepare("SELECT * FROM famcomp WHERE app_id='". mysql_real_escape_string($app_id) ."'");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<td><input type="hidden" name="app_id[]" value="<?php echo $row['app_id']; ?>" /></td>
<td><input type="text" name="fullname[]" value="<?php echo $row['fullname']; ?>" class="input" /></td>
<td><input type="text" name="fage[]" value="<?php echo $row['fage']; ?>" class="input" /></td>
<td><input type="text" name="frel[]" value="<?php echo $row['frel']; ?>" class="input" /></td>
<td><input type="text" name="fcivil[]" value="<?php echo $row['fcivil']; ?>" class="input" /></td>
<td><input type="text" name="fedu[]" value="<?php echo $row['fedu']; ?>" class="input" /></td>
<td><input type="text" name="foccup[]" value="<?php echo $row['foccup']; ?>" class="input" /></td>
<td><input type="text" name="finco[]" value="<?php echo $row['finco']; ?>" class="input" /></td>
</tr>
<?php
}
?>
<br></table></form>
saveupdaterecord.php
$fullname=$_POST['fullname'];
$N = count($fullname);
for($i=0; $i < $N; $i++)
mysql_query("UPDATE 'famcomp' SET 'fullname' = '".$_POST["fullname[$i]"]."', fage = '".$_POST["fage[$i]"]."', frel = '".$_POST["frel[$i]"]."', fcivil = '".$_POST["fcivil[$i]"]."', fedu = '".$_POST["fedu[$i]"]."', foccup = '".$_POST["foccup[$i]"]."', finco = '".$_POST["finco[$i]"]."' WHERE `app_id` = '".$_POST["app_id"]."'"); // Run the Mysql update query inside for loop
$message = 'Success Updating the record!!';
echo "<SCRIPT>alert('$message');</SCRIPT>";
echo "<script>windows: location='editrecord.php?name=$a'</script>";
Remove quotes to table name and Use foreach for looping the data.
foreach($fullname as $key){ mysql_query("UPDATE famcomp SET 'fullname' = '".$_POST[fullname[$key]]."', fage = '".$_POST["fage[$key]"]."', frel = '".$_POST["frel[$key]"]."', fcivil = '".$_POST["fcivil[$key]"]."', fedu = '".$_POST["fedu[$key]"]."', foccup = '".$_POST["foccup[$key]"]."', finco = '".$_POST["finco[$key]"]."' WHEREapp_id= '".$_POST["app_id"]."'"); }
Dont use 'famcomp' use famcomp
Also as raveenanigam said you havent used $_POST["app_id[$i]"]. If still gets the problem, try using
mysql_query("UPDATE famcomp SET
fullname = '".$_POST["fullname[$i]"]."', fage = '".$_POST["fage[$i]"]."',
frel = '".$_POST["frel[$i]"]."', fcivil = '".$_POST["fcivil[$i]"]."',
fedu = '".$_POST["fedu[$i]"]."', foccup = '".$_POST["foccup[$i]"]."',
finco = '".$_POST["finco[$i]"]."'
WHERE `app_id` = '".$_POST["app_id[$i]"]."'")
or die(mysql_error()); // Run the Mysql update query inside for loop
Edit : Try this
if(isset($_POST['fullname']))
{
$fullname = $_POST['fullname'];
echo "Got the Fullname";
foreach( $fullname as $key => $n ) {
mysql_query("UPDATE famcomp SET 'fullname' = '".$_POST[fullname[$key]]."', fage = '".$_POST["fage[$key]"]."', frel = '".$_POST["frel[$key]"]."', fcivil = '".$_POST["fcivil[$key]"]."', fedu = '".$_POST["fedu[$key]"]."', foccup = '".$_POST["foccup[$key]"]."', finco = '".$_POST["finco[$key]"]."' WHERE app_id= '".$_POST["app_id[$key]"]."'") or die(mysql_error());
$message = 'Success Updating the record for ' . $n;
}
}
else
echo "Cannot get Fullname";
Try this
$fullname=$_POST['fullname'];
$N = count($fullname);
for($i = 0 ;$i< count($fullname); $i++) {
$query = "UPDATE famcomp SET app_id = '".$_POST["app_id[$i]"]."', fullname = '".$_POST["fullname[$i]"]."', fage = '".$_POST["fage[$i]"]."', frel = '".$_POST["frel[$i]"]."', fcivil = '".$_POST["fcivil[$i]"]."', fedu = '".$_POST["fedu[$i]"]."', foccup = '".$_POST["foccup[$i]"]."', finco = '".$_POST["finco[$i]"]."' WHERE app_id = '".$_POST["app_id[$i]"]."'"; // Run the Mysql update query inside for loop
mysql_query($query, $con);
$message = 'Success Updating the record!!';
echo "<SCRIPT>alert('$message');</SCRIPT>";
echo "<script>windows: location='editrecord.php?name=$a'</script>";
}
Add this to your php
<?php
$result = $db->prepare("SELECT * FROM famcomp WHERE app_id='". mysql_real_escape_string($app_id) ."'");
$result->execute();
for($i=0; $row = $result->fetch(); $i++)
$con = mysql_connect("host","user","password","database"); //you can check this in priviledges. name of your database, if user has no password do not include password, delete "password",
if (!$con){
die("Can't connect".mysql_error());
}
mysql_select_db("database",$con); //the name of your database
?>

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'].

multiple checkbox post form

The below code will only work with one checkbox and ignores the rest. Is there any way that I can have it to delete selected checkboxes? I have tried using implode but it gives me
Warning: implode(): Invalid arguments passed
<form action="" method="post">
<input type="checkbox" name="id" class="check" value = "<?php echo $row['id']; ?>">
<?php echo $row['to_user'];?>
<input type="submit" name="delete">
</form>
<?php
if (isset($_POST['delete'])) {
$id = $_POST['id'];
$ids = implode( ',', $id );
$mydb = new mysqli('localhost', 'root', '', 'database');
$stmt = $mydb->prepare("update messages set deleted = 'yes' where from_user = ? and id = ? ");
$stmt->bind_param('ss', $user, $ids);
$stmt->execute();
echo "Message succesfully deleted";
exit();}
?>
Give the checkbox an array-style name:
<input type="checkbox" name="id[]" class="check" value = "<?php echo $row['id']; ?>">
This will cause $_POST['id'] to be an array of all the checked values. Then delete them in a loop:
$mydb = new mysqli('localhost', 'root', '', 'database');
$stmt = $mydb->prepare("update messages set deleted = 'yes' where from_user = ? and id = ?");
$stmt->bind_param('ss', $user, $id);
foreach ($_POST['id'] as $id) {
$stmt->execute();
}
You can't use a comma-separated list of IDs with =. You can use it with id in (...), but you can't do parameter substitution with this because the number of elements isn't known. So the loop is th best way to do it.

Categories