saving data from an array without submitting any form php - php

I'm tryng to save an array so I have the following code:
<?php
$sql = "SELECT * FROM scenarii where code_s='".mysql_real_escape_string($_POST['code_s'])."'";
$qry = mysql_query($sql) or die(__LINE__.mysql_error().$sql);
$i = -1; // index des enregistrements
?>
<table cellpadding="5" cellspacing="5">
<tr>
<td><strong>CODE SCENARIO</strong></td>
<td><strong>LIBELLE</strong></td>
<td><strong>ACTION</strong></td>
<td><strong>DESCRIPTION</strong></td>
<td><strong>DATE</strong></td>
</tr>
<form action="<?php echo (isset($_POST['go'])) ? 'go.php' : '#'; ?>" method="post">
<input type="hidden" name="liasse" value="<?php echo $_POST['liasse']; ?>"/>
<input type="hidden" name="n_doss" value="<?php echo $_POST['n_doss']; ?>"/>
<input type="hidden" name="qualite" value="<?php echo $_POST['qualite']; ?>"/>
<?php while($row = mysql_fetch_assoc($qry)): ?>
<tr>
<td><input name="data[<?php echo ++$i; ?>][code_s]" type="text" value="<?php echo $row['code_s'];?>" size="10"></td>
<td><input name="data[<?php echo $i; ?>][titre]" type="text" value="<?php echo $row['titre']; ?>" size="45"></td>
<td><input name="data[<?php echo $i; ?>][action]" type="text" value="<?php echo $row['action']; ?>" size="15"></td>
<td><input name="data[<?php echo $i; ?>][libelle]" type="text" value="<?php echo $row['libelle']; ?>" size="55"></td>
<td><input type="text" name="data[<?php echo $i; ?>][date]" value="<?php echo $get_date($row['jour']) ; ?>" size="12"></td>
</tr>
<?php endwhile; ?>
And in order to save this I have this code:
if (isset($_POST['liasse'])) {
$value = $_POST['data'] ;
foreach($value as $key => $array)
{
$sql = 'INSERT INTO agenda SET
liasse = "'.mysql_real_escape_string($_POST['liasse']).'",
code_s = "'.mysql_real_escape_string($array['code_s']).'",
date_action = "'.date('Y-m-d',strtotime($array['date'])).'",
libelle = "'.mysql_real_escape_string($array['titre']).'",
action = "'.mysql_real_escape_string($array['action']).'",
description = "'.mysql_real_escape_string($array['libelle']).'",
n_doss = "'.mysql_real_escape_string($_POST['n_doss']).'",
qualite = "'.mysql_real_escape_string($_POST['qualite']).'"
';
mysql_query($sql) or die(__LINE__.mysql_error().$sql);
}
But I'm really lost,
In fact I use a form for that, now I would like to submit all of this data but without any form, directly when I have the first while I would like to save it.
The thing is that I'm lost because I can not call any var like that data[][code_s].
So I do not know how to save this. I would like to save it in background, and not to display that something has been saved.
Receive all my Utmost Respect
kind regards,
SP.

Wrap the code od the lower code block into a function and hand over the value array as argument:
function storeValues ($data) {
foreach($data as $key => $val)
{
$catalog=sprintf("%s='%s'",$key,$val);
$sql = sprintf('INSERT INTO agenda SET %s', implode(',',$catalog));
mysql_query($sql) or die(__LINE__.mysql_error().$sql);
} // foreach
} // function storeValues
You call this function when you want to save the values. So after retrieving them from the database. You call it for each row you retrieve and hand over the values like that:
storeValues ($row);
This will store one row of values at a time. Obviously this can be optimized to use a multiple insert. But let's take one step after another...

Related

Form send data to php with multiple inputs with the same name

I'm trying make a form where me or user can insert data. Some parts are coming form data base like: Work name and work price. In input fields can insert work amount. In each input row have checkbox, if checkbox ar checked, that row will be seen in php.
<table class="table">
<thead>
<tr>
<th scope="col">*</th>
<th scope="col">Work name</th>
<th scope="col">Quantity</th>
<th scope="col">Price for unit</th>
<th scope="col">Total price</th>
</tr>
</thead>
<form method="POST" action="process/pdf.process.php">
<tbody>
<?php
$works = ORM::for_table('work')->find_many();
foreach($works as $work){
?>
<tr id="<?php echo $work->id; ?>">
<td><input type="checkbox" name="useit[]" value="<?php echo $work->id; ?>"/></td>
<td><?php echo $work->name; ?></td>
<td><input type="text" placeholder="" class="amount"/> <?php echo $work->unit; ?></td>
<td class="work_price" data="<?php echo $work->price; ?>"><?php echo $work->price.'€/'.$work->unit; ?></td>
<td class="total_price">0€</td>
<input type="" name="work_id[]" value="<?php echo $work->id; ?>" />
<input type="hidden" name="work_name[]" value="<?php echo $work->name; ?>" />
<input type="hidden" name="amount[]" class="<?php echo $work->id; ?>_copy_amount" value="" />
<input type="hidden" name="unit[]" value="<?php echo $work->unit; ?>" />
<input type="hidden" name="unit_price[]" value="<?php echo $work->price; ?>€" />
<input type="hidden" name="unit_total[]" class="<?php echo $work->id; ?>_copy_total" value="" />
</tr>
<?php
}
?>
</tbody>
<input type="submit" name="do_pdf" value="Pga jkāuztaisa ar jquery" />
</form>
</table>
Now, there is php, but how can i show only checked rows in while loop?
<?php
$data = array();
$work_id = array();
$work_names = $_POST['work_name'];
$amounts = $_POST['amount'];
$units = $_POST['unit'];
$units_prices = $_POST['unit_price'];
$units_total = $_POST['unit_total'];
if(isset($_POST['useit'])){
$work_id = $_POST['useit'];
}
$data = array($work_id, $work_names, $amounts, $units, $units_prices, $units_total);
echo '<pre>';
echo htmlspecialchars(print_r($data, true));
echo '</pre>';
?>
There are different possibilities how to do that. One Suggestion (i limit it to the parts which are relevant)
form (note that i gave work_name the id as an index, use_it not (but it could have)
<td><input type="checkbox" name="useit[]" value="<?php echo $work->id; ?>"/></td>
<input type="hidden" name="work_name[<?php echo $work->id?>]" value="<?php echo $work->name; ?>" />
The form only submits the checked checkboxes values in an array, all other are omited. Therefore we could loop over the checked checkbox values like this
foreach($_POST['useit'] as $work_id){
$work_name = $work_names[$work_id];
//do something with the checked rows only (all others are not looped over)
}
This is only possible, due to the given id as an array key in the form work_name[<?php echo $work->id?>].
A general sidenote for better (and more secure) code: please note that your data could be modified by the user, and send back with wrong data (or worse). So please make sure to sanitize your input, or probably better in this case only submit the id in question and the new data and pickup the rest directly from your database. So you can make sure the hidden data has not been modified on the client side and send back wrong.

( PHP /JQuery?) Get the table row value when the checkbox is checked

It's a table, each row consists a checkbox, when it's checked, would like to get the respective td values and echo out. Here im using the if statement, but it doesn't seems to work.
And iam using php here, is using jquery a way out, can jquery work with php
code, so could i send those checked table row values back to serve? Any thoughts? Thank you.
<form>
<table>
<tr>
<?php
$specific = [];
while($row = mysqli_fetch_array( $result ,MYSQL_ASSOC)) {?>
<td><input type="checkbox" name="p[]" value="<?php echo $row['id']; ?>">
</td>
<td><input type="text" name="patientid[]"
style="border: none" value="<?php echo $row['patientid'] ?>"></td>
<td>
<textarea name="msg" style="border: none" class='msg'>
<?php echo $row['message'];} ?> </textarea>
</td>
<td><input class="phone" type="text" value="<?php echo
$row['telMobile'] ?>"></td>
check whether table row(s) are checked
<?php if(!isset($_GET['p'])){
$specific[] = [
"phone" => $row["telMobile"],
"message" =>$row["message"],
];}
}
$result = json_encode($specific,JSON_UNESCAPED_UNICODE);
echo $result;
echo "</tr>";
echo "</table>";
echo "</form>";?>
The desired result for $result is to show only the data of the table row(s) that are checked.
[{"phone":"123456","message":"test"},
{"phone":"789456","message":"testing"}]
Change your HTML code as below:
<td><input type="text" name="patientid[<?php echo $row['id']; ?>]"
style="border: none" value="<?php echo $row['patientid'] ?>"></td>
<td>
<textarea name="msg[<?php echo $row['id']; ?>]" style="border: none" class='msg'>
<?php echo $row['message'];} ?> </textarea>
</td>
<td><input name="phone[<?php echo $row['id']; ?>]" class="phone" type="text" value="<?php echo
$row['telMobile'] ?>"></td>
I have added <?php echo $row['id']; ?> in the input control name.
Change your PHP code as below:
foreach($_GET["p"] as $id) {
$specific[] = [
"phone" => $_GET["phone"][$id],
"message" => $_GET["msg"][$id],
];
}

Trouble with catching values from a multidimensional array and display it in the text field where it was originally entered when form was submitted

I need help on how to retain the entered values in the text fields where user entered the value after submit. I'm having difficulty trying to figure out how to retain the values, because when I click on the submit button, the page refreshes and then values gone, and I have to retype them again.
Below is my form:
<?php $count_name = count($x); ?>
<table>
<thead>
<tr>
<th colspan="<?php echo $count_name; ?>"><strong>MR</strong></th>
<th colspan="<?php echo $count_name; ?>"><strong>MS</strong></th>
</tr>
</thead>
<tbody>
<?php $_college = mysql_query("SELECT * FROM college");
if(mysql_num_rows($_college)) {
$i=0;
while($row_college=mysql_fetch_array($_college)) { ?>
<tr>
<?php for($j=0;$j<$count_name;$j++) { ?>
<td>
<input type="text" name="mr<?php echo $j; ?>[]" value=""/>
<td>
<?php } for($k=0;$k<$count_name;$k++) { ?>
<td>
<input type="text" name="ms<?php echo $k; ?>[]" value=""/>
<td>
<?php } ?>
</tr>
<?php } $i++;} ?>
</tbody>
<table>
<input type="hidden" value="<?php echo $count_name; ?>" name="totrows"/>
<input type="submit" value="Submit" name="submit"/>
Here's my code if button submit is click
<?php
if(isse($_POST['submit'])) {
$y = $_POST['totrows'];
$count_totcriteria = $y;
for($ab=0;$ab<$count_totcriteria;$ab++) {
$mr = 'mr_'.$ab;
$ms = 'ms_'.$ab;
$mr_score = $_POST[$mr];
$ms_score = $_POST[$mr];
foreach($mr_score as $key1 => $val1) {
if(is_numeric($val1) && !empty($val1)) {
$mr_val[] = $val1;
} else {
$msg = 'All fields are required and must be a valid score';
}
}
foreach($ms_score as $key2 => $val2) {
if(is_numeric($val2) && !empty($val2)) {
$ms_str[] = $val2;
} else {
$msg = 'All fields are required and must be a valid score';
}
}
}
}
I know I have to put some code in the 'value=""' in order to display back the entered values when form is submitted but I am not sure what code to use. Not sure how to catch each array values.
I think instead of
<input type="text" name="mr<?php echo $j; ?>[]" value=""/>
you are looking for something like this (assuming $i is your new outer loop)
<input type="text" name="mr_<?= $j ?>[<?= $i ?>]" value="<?= #$_POST['mr_'.$j][$i] ?>"/>
and the same change for the ms line.
Does that work?

PHP page is storing form input variables after user submits

I wasn't sure what else to call the title...I have a PHP page that accesses a certain MySQL database, pulls the values from the table, and places them in an HTML form (POST method - PHP_SELF). The user can then view the values, alter them as they wish, and submit them. The page then takes those values and updates the MySQL database. Everything works perfectly except that when the user submits and the page goes to show the new updated variables, it still shows the old values. The user is forced refresh the page before the new variables show up. I thought that PHP was perhaps not deleting the variables, so I unset all stored variables after the script was over and it's still not working. I ever tried putting a sleep timer before the script started, and that didn't work either. I'd appreciate any suggestions. Here is my script just for reference:
<html>
<body>
<?php
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
?>
</body>
</html>
You are displaying the data from the database before you update it.
It is normally good practice to do all your database connectivity at the top of the page, then display the results.
In your code (even if a user has submitted an update), you query the data, pull it from database and display it, then run the update with what the user submitted.
Changing your code to this should do the trick (Do read the note below though):
<html>
<body>
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
</body>
</html>
Bad note - your code is wide open to injection attacks. You are using form data with no verification. That's a big red flag. Secondly, you are using deprecated mysql_* functions. Your code should be using mysqli_* functions or better yet move to PDO. It is much safer and you will be able to do a lot more with it.
Edit 2: The page IS being updated after the user submits the form, but the page you display to the user is querying the database before you update it - and using that to display the page to the user.

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