I have a dynamic form that allows users to enter information and that form can be submitted multiple times and the page will show all of the inputted data thanks to $_SESSION. That information is sent to another page where it will be saved to a MySQL database after submission.
I can't get it to save all of the information. If I have 3 groups of data, it will only write the last one into the database. How do I save the entire array to the database?
This is the page that shows all of the dynamic information:
<?php
$invoice_no = $_SESSION['invoice'];
if(isset($_SESSION['order'])) :
foreach($_SESSION['order'] as $sav) {
?>
<form action="addrow.php" method="post">
<label>Length</label><input type="text" name="length" value="<?php echo $sav['length']; ?>" size="2">
<label>Width</label><input type="text" name="width" value="<?php echo $sav['width']; ?>" size="2">
<label>Color</label><input type="text" name="color" value="<?php echo $sav['color']; ?>" size="4">
<label>Quantity</label><input type="text" name="quantity" value="<?php echo $sav['quantity']; ?>" size="2">
<label>Invoice Is Hidden</label><input type="hidden" name="invoice" value="<?php echo $invoice_no; ?>">
<input type="hidden" name="total" value="<?php echo $sav['total']; ?>" />
<input type="hidden" name="PaymentStatus" value="PAID">
<br>
<?php } endif; ?>
<br><br>
<input type="submit" value="Submit" name="upload">
</form>
This page saves it to the database. I was unsure of how to save the array into the database, so I used the same code to show the session data and I modified it but failed:
<?php
require("addrow_info.php");
if(isset($_POST['upload'])) :
$decal = array(
'length' => $_POST['length'],
'width' => $_POST['width'],
'color' => $_POST['color'],
'quantity' => $_POST['quantity'],
'total' => $_POST['total'],
'invoice' => $_POST['invoice'],
'paymentStatus' => $_POST['PaymentStatus'],
'submit' => $_POST['upload']
);
$_POST['order'][] = $decal;
endif;
if(isset($_POST['order'])) :
foreach($_POST['order'] as $newOrder) {
// Opens a connection to a MySQL server
$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = "INSERT INTO orders (PaymentStatus, invoice_no, length, width, color, quantity, total ) VALUES ('".$newOrder['paymentStatus']."','".$newOrder['invoice']."','".$newOrder['length']."', '".$newOrder['width']."', '".$newOrder['color']."', '".$newOrder['quantity']."', '".$newOrder['total']."')";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
echo "$query";
mysql_close();
}
} endif;
header ("location:/thankyou.php");
?>
I was reading about using the serialize() function but I'm not sure if that's best for what I'm trying to accomplish. I want each group of data to save in one row under their respective column.
It should look like this:
Length Width Color Invoice Quantity Total PaymentStatus
5 5 Green abc123 1 2.00 PAID <--Each row is a group
6 6 blue def234 2 3.00 PAID
What is the best solution for saving an array into a MySQL database?
<form action="addrow.php" method="post"><?php
$invoice_no = $_SESSION['invoice'];
if(isset($_SESSION['order'])) :
foreach($_SESSION['order'] as $sav) {
?>
<label>Length</label><input type="text" name="length[]" value="<?php echo $sav['length']; ?>" size="2">
<label>Width</label><input type="text" name="width[]" value="<?php echo $sav['width']; ?>" size="2">
<label>Color</label><input type="text" name="color[]" value="<?php echo $sav['color']; ?>" size="4">
<label>Quantity</label><input type="text" name="quantity[]" value="<?php echo $sav['quantity']; ?>" size="2">
<label>Invoice Is Hidden</label><input type="hidden" name="invoice[]" value="<?php echo $invoice_no; ?>">
<input type="hidden" name="total[]" value="<?php echo $sav['total']; ?>" />
<input type="hidden" name="PaymentStatus" value="PAID">
<br>
<?php } endif; ?>
<br><br><input type="submit" value="Submit" name="upload">
</form>
try it and print_r( $_POST ), I think you can make it.
if(isset($_POST['upload'])) {
print_r($_POST);
}
Array ( [length] => Array ( [0] => 2 [1] => 3 [2] => 4 ) [width] => Array ( [0] => 2 [1] => 3 [2] => 3 )
for($i=0;$i<count($_POST['length']);$i++){
$order = array(
'length'=>$_POST['length'][$i],
'width'=>$_POST['width'][$i]),
//...............
);
$sql = "INSERT INTO orders (PaymentStatus, invoice_no, length, width, color, quantity, total ) VALUES ('{$order['paymentStatus']}','{$order['invoice']}','{$order['length']}', '{$order['width']}', '{$order['color']}', '{$order['quantity']}', '{$order['total']}')";
mysql_query($sql);
}
Related
I Am trying to edit user details from a database. I have queried the database and stored the info in $row, but each time I try to echo the details I get the following error: Trying to access array offset on the value of type null in
C:\xampp\htdocs\merchant\admin\edituserhis.php
I seem not to know what I am doing wrong in the SQL statement, I have checked the Variable $id and its working well.
<div class="quotes">
<?php
$con = mysqli_connect("localhost","root","","merchant_db");
$id = $_REQUEST['username'];
$query = "SELECT * from user_trans where userid='".$id."'";
$result = mysqli_query($con, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
?>
<?php echo $row['userid']; ?>;
<form name="form" method="post" action="userprofile.php">
<input type="hidden" name="new" value="1" />
<input name="id" type="hidden" value="<?php echo $row['userid'];?>" />
<p><input type="text" name="balance" placeholder="Enter Amount" required value="<?php echo $row['description'];?>" /></p>
<p><input name="submit" type="submit" value="Credit" /></p>
</form>
</div>
Is it possible to update multiple records in one MySQLi query?
There are 4 records to be updated (1 for each element level) when the submit button is clicked.
The results are posted to a separate PHP page which runs the query and returns the user back to the edit page. elementid is 1,2,3,4 and corresponds with Earth, wind, fire, water. These never change (hence readonly or hidden)
<form id="edituser" name="edituser" method="post" action="applylevelchanges.php">
<fieldset>
<legend>Edit Element Level</legend>
<?php
while($userdetails->fetch())
{?>
<input name="clientid" id="clientid" type="text" size="8" value="<?php echo $clientid; ?>" hidden />
<input name="elementid" id="elementid" type="text" size="8" value="<?php echo $elementid;?>" hidden />
<input name="elemname" id="elemname" type="text" size="15" value="<?php echo $elemname; ?>" readonly />
<input name="elemlevel" id="elemlevel" type="text" size="8" required value="<?php echo $elemlevel; ?>" /></br>
</br>
<?php }?>
</fieldset>
<button type="submit">Edit Student Levels</button>
</form>
And the code to apply the changes
<?php
if (isset($_POST['clientid']) && isset($_POST['elementid']) && isset($_POST['elemname']) && isset($_POST['elemlevel'])) {
$db = createConnection();
$clientid = $_POST['clientid'];
$elementid = $_POST['elementid'];
$elemname = $_POST['elemname'];
$elemlevel = $_POST['elemlevel'];
$updatesql = "update stuelement set elemlevel=? where clientid=? and elementid=?";
$doupdate = $db->prepare($updatesql);
$doupdate->bind_param("iii", $elemlevel, $clientid, $elementid);
$doupdate->execute();
$doupdate->close();
$db->close();
header("location: edituserlevel.php");
exit;
} else {
echo "<p>Some parameters are missing, cannot update database</p>";
}
I need to write a PHP program that will keep score of a bowling game. I can handle the calculation of the scores that is not the problem. My problem is getting the data into arrays in the first place.
My idea is to have an array for each player like below:
$scores = array(
array(
'name' => 'Player 1',
'sheet' => '10,10,10,10,10,10,10,10,10,10,10,10'
),
array(
'name' => 'Player 2',
'sheet' => '10,10,10,10,10,10,10,10,10,10,10,10'
),
);
I wanted to have an initial form where you can enter the player names, this then creates the arrays and afterwards create another form for each player (array) to enter the scores.
What would be the best way to go about doing this?
Thanks
Edit: Will this work?
<input maxlength="30" name="players[1][player1]" size="30" type="text" />
<input maxlength="30" name="players[2][player2]" size="30" type="text" />
So the first form as show above will create the arrays and the the player name value. The second form like the below would add the scores, although I cant seem to get this to work.
<input maxlength="30" name="players[1][score]" size="30" type="text" />
<input maxlength="30" name="players[2][score]" size="30" type="text" />
Here is a small example. Perhaps buggy but it should work (for inspiration)
<h1>Bowling</h1>
<?php
if ( isset ( $_POST['next'] ) ) {
if ( isset ( $_POST['players'] ) ) {
$exp = explode("\n", trim($_POST['players']));
echo "<h2>Input Score</h2>";
echo '<form method="post" action="bowling.php">';
foreach ( $exp as $p ) {
if ( trim($p) != '') {
$name = trim(htmlspecialchars($p));
echo '<fieldset>';
echo '<label><h3>Input "' .$name.'" score</h3></label>';
echo '<input style="width:100%" type="text" name="score[]" placeholder="Put in the score for ' . $name . '. Just for example 1 2 3 4 5">';
echo '<input type="hidden" name="player[]" value="'.$name.'">';
echo '</fieldset>';
}
}
echo '<input type="submit" name="next" value="Results">';
echo '</form>';
}
if ( isset($_POST['score'], $_POST['player']) ) {
echo "<h2>Results</h2>";
$i = 0;
$result = [];
foreach ( $_POST['player'] as $name ) {
$result[$name] = $_POST['score'][$i];
$i++;
}
var_dump($result);
}
} else {
?>
<form method="post" action="bowling.php">
<textarea style="width:500px; height:500px;" name="players" placeholder="One player in each line and everything will be fine"></textarea>
<input name="next" type="submit">
</form>
<?php
} ?>
Im confused. I have been analyzing this for hours..
What I want:
"EACH table row with the checkbox thats checked would be updated with the value inputted."
Anyone can help?
thank you,
Leo
Admin.php
function submit_acc(){
$this->access_chk(); //CHECK USER ACCESS
$this->form_validation->set_error_delimiters(' ', '<br />');
$checkbox=$this->input->post('cek');
$sbm=$this->input->post('sbm');
if($sbm == "Update" && $checkbox!=false){
foreach ($checkbox as $row_id) {
// echo($this->input->post('bank_accname'));
$this->form_validation->set_rules("type", "bank name", "required");
$this->form_validation->set_rules("isactive", "Status Bank", "required");
if(!$this->form_validation->run()){ exit(validation_errors()); }
echo "update x where y =$row_id";
echo $_POST["accgroup"].$_POST["type"].$this->input->post('bank_accname').$_POST["bank_accnumber"].$_POST["isactive"];
$data[] = array (
"acc_id" => $row_id,
"acc_accgroup_id" => $_POST["accgroup"],
"acc_bank_name" => $_POST["type"],
"acc_bank_accname" => $this->input->post('bank_accname'),
"acc_bank_accnumber" => $_POST["bank_accnumber"],
"acc_isactive" => $_POST["isactive"]
);
$uid=$row_id;
// echo $uid;
}
//var_dump($data);
//var_dump($checkbox);
$this->db->update_batch('acc', $data, 'acc_id');
exit("end");
View.php
<form action="<?php echo site_url("admin/submit_acc"); ?>" method="post" id="form">
<table>
<tr >
<td align="center"><?php echo $i; ?></td>
<input type="hidden" name="id[]" value="<?php if(isset($r)) echo $r["acc_id"]; ?>" />
<input type="hidden" name="isactive[]" value="<?php if(isset($r)) echo $r["acc_isactive"]; ?>" />
<td><input type="text" class="textbox" style="width:200px;" value="<?php if(isset($r)) echo $r["acc_bank_name"]; ?>" name="type[]" id="type" /></td>
<td><input type="text" class="textbox" style="width:200px;" value="<?php if(isset($r)) echo $r["acc_bank_accname"]; ?>" name="bank_accname[]" id="bank_accname" /></td>
<td><input type="text" class="textbox" style="width:200px;" value="<?php if(isset($r)) echo $r["acc_bank_accnumber"]; ?>" name="bank_accnumber[]" id="bank_accnumber" /></td>
<!--<input type='radio' name="isactive_<?php echo $r['acc_id'];?>" value=1
<?php if ($r["acc_isactive"]=='1') echo 'checked'; ?> > -->
G
<select name="accgroup[]">
<option value='<?php echo $r["accgroup_no"]; ?>' id="account_id"><?php echo $r['accgroup_no']; ?></option>
<?php echo $stropt; ?></select>
<!-- <input type='radio' name='isactive_<?php echo $r['acc_id'];?>' value=0 <?php if ($r["acc_isactive"]=='0')echo 'checked'; ?>> Off -->
" >
</table>
</form>
MY TRY AND ITS NOT WORKING : if I dont select the first row, the second row wont be updated . the point is my checkbox should be checked all to function properly. if not, it would start updating the rows according to numbers of checked checkboxes. Can somebody please tell me what did I miss?????
$data=array();
$data['checkbox']=$this->input->post('cek');
$data['id']=$this->input->post('id',true);
$data['accgroup']=$this->input->post('accgroup',true);
$data['type']=$this->input->post('type',true);
$data['bank_accname']=$this->input->post('bank_accname',true);
$data['bank_accnumber']=$this->input->post('bank_accnumber',true);
$data['isactive']=$this->input->post('isactive',true);
$sbm=$this->input->post('sbm');
if($sbm == "Update" && $data['checkbox']!=false){
foreach ($data['checkbox'] as $key => $each) {
// echo($this->input->post('bank_accname'));
echo $data["accgroup"][$key];
$this->form_validation->set_rules("type", "bank name", "required");
$this->form_validation->set_rules("isactive", "Status Bank", "required");
if(!$this->form_validation->run()){ exit(validation_errors()); }
$temp[] = array (
"acc_id" => $data["id"][$key] ,
"acc_accgroup_id" => $data["accgroup"][$key],
"acc_bank_name" => $data["type"][$key],
"acc_bank_accname" => $data['bank_accname'][$key],
"acc_bank_accnumber" => $data["bank_accnumber"][$key],
"acc_isactive" => $data["isactive"][$key]
);
$uid=$key;
// echo $uid;
}
var_dump($temp);
//var_dump($checkbox);
$this->db->update_batch('acc', $temp, 'acc_id');
exit("end");
I have a update form that populates from a database dynamically, I have two checkboxes in my form that post to an array so I can hit one submit button and update all rows with a foreach statement. The text fields work as they should, but when the checkbox fields post to their array, they leave out the zeros my arrays become shorter.
How do I add 0 where a null checkbox would be?
this is my form
<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">
<input type="hidden" name="ss_id[]" value="<?php echo $row_rsSnapshot['ss_id']; ?>" />
<input type="hidden" name="ss_yearmonth[]" value="<?php echo htmlentities($row_rsSnapshot['ss_yearmonth'], ENT_COMPAT, 'UTF-8'); ?>" />
<tr>
<td>
<input <?php if (!(strcmp($row_rsSnapshot['ss_inventory'],1))) {echo "checked=\"checked\"";} ?> type="checkbox" name="ss_inventory[]" value="" <?php if (!(strcmp(htmlentities($row_rsSnapshot['ss_inventory'], ENT_COMPAT, 'UTF-8'),""))) {echo "checked=\"checked\"";} ?> />
</td>
<td>
<input <?php if (!(strcmp($row_rsSnapshot['ss_write_off'],1))) {echo "checked=\"checked\"";} ?> type="checkbox" name="ss_write_off[]" value="" <?php if (!(strcmp(htmlentities($row_rsSnapshot['ss_write_off'], ENT_COMPAT, 'UTF-8'),""))) {echo "checked=\"checked\"";} ?>
</td>
<td>
<input type="text" name="ss_date[]" value="<?php echo htmlentities($row_rsSnapshot['ss_date'], ENT_COMPAT, 'UTF-8'); ?>" size="32" />
</td>
<td>
<input type="text" name="ss_transaction[]" value="<?php echo htmlentities($row_rsSnapshot['ss_transaction'], ENT_COMPAT, 'UTF-8'); ?>" size="32" />
</td>...
And here is my sql update query
foreach($_POST['ss_id'] as $key=>$ss_id){
$ss_inventory = GetSQLValueString(isset($_POST['ss_inventory'][$key]) ? "true" : "", "defined","1","0");
$ss_write_off = GetSQLValueString(isset($_POST['ss_write_off'][$key]) ? "true" : "", "defined","1","0");
$ss_date = $_POST['ss_date'][$key];
$ss_transaction = $_POST['ss_transaction'][$key];
$ss_debit = $_POST['ss_debit'][$key];
$ss_credit = $_POST['ss_credit'][$key];
$ss_yearmonth = $_POST['ss_yearmonth'][$key];
$sql = "UPDATE snapshot SET ss_inventory = '$ss_inventory', ss_write_off = '$ss_write_off', ss_date = '$ss_date', ss_transaction = '$ss_transaction', ss_debit = '$ss_debit', ss_credit = '$ss_credit' , ss_yearmonth = '$ss_yearmonth' WHERE ss_id = '$ss_id' ";
mysql_select_db($database_connMyayla, $connMyayla);
$Result1 = mysql_query($sql, $connMyayla) or die(mysql_error());
}
}
mysql_close();
?>
this solved it
If anyone is interested...
I put a counter to find out how many rows are being populated with this query and inserted that into my checkbox name array...
$i = 0;
do {
...
<td>
<input <?php if (!(strcmp($row_rsSnapshot['ss_inventory'],1))) {echo "checked=\"checked\"";} ?> type="checkbox" name="ss_inventory[<?php echo $i;?>]" value="" <?php if (in_array($i, $ss_inventory)) echo "checked='checked'"; ?> />
</td>
<td>
<input <?php if (!(strcmp($row_rsSnapshot['ss_write_off'],1))) {echo "checked=\"checked\"";} ?> type="checkbox" name="ss_write_off[<?php echo $i;?>]" value="" <?php if (in_array($i, $ss_write_off)) echo "checked='checked'"; ?> />
</td>
....
$i++;
} while ($row_rsSnapshot = mysql_fetch_assoc($rsSnapshot));
now the checkboxes that are checked will correspond with the correct array number..
e.g.
lets say you have 4 rows of data, but you only check the checkboxes for row 2 and 4.
//run this to see your result
print_r($_POST['ss_inventory']);
//outputs: Array ([1] => [3] =>)
Before this was my output, everything was pushed up to the start of my array because the false checkboxes were not being submitted or NULL. so rows 1 and 2 would result true.
//outputs: Array ([0] => [1] =>)
Also See
Checkbox "checked"-value jumps up to earlier array values, when array is empty
The browser does not submit unchecked checkboxes. You'll need to either give unique names, or simply use radio buttons.