sending while loop radio button data to database using php - php

The first two values of the radio are not being inserted, is there any problem with the condition in for loop?
I have the html code(form) and the php code on the bottom
<?php
$i=1;
$name=$data['username'];
$sql1 = "SELECT * from membre where groupe='$name'";
$run1 = mysqli_query($db,$sql1);
while($row = mysqli_fetch_assoc($run1)){
?>
<tr>
<td> <?php echo $i; $i++; ?></td>
<td style="display: none;" ><input value="<?php echo $i; ?>" name="id[]" class="form-control" readonly="readonly" > </td>
<td ><input value="<?= $row['nom']; ?>" name="nom1[]" class="form-control" readonly="readonly" > </td>
<td><input type="radio" name="presence[<?php echo $i; ?>]" value="Présent"></td>
<td><input type="radio" name="presence[<?php echo $i; ?>]" value="Absent"></td>
</tr>
<?php
}
?>
for($i=0; $i<$_POST['id'][$i]; $i++) {
$id = mysqli_real_escape_string($db,trim($_POST['id'][$i]));
$nom1= mysqli_real_escape_string($db,trim($_POST['nom1'][$i]));
$presence= mysqli_real_escape_string($db,trim($_POST['presence'][$i]));
$v1 = "INSERT INTO presence(rapport_id,groupe,dat,nom,presence) values('$rapport_id','$groupe','$dat','$nom1','$presence')";
$r = mysqli_query($db,$v1);

$i<$_POST['id'][$i] is not the correct looping condition. You should be using the length of $_POST['id'] as the loop limit.
Or just use foreach. And also use a prepared statement instead of substituting variables directly into the query.
$stmt = $db->prepare("INSERT INTO presence(rapport_id,groupe,dat,nom,presence) values(?, ?, ?, ?, ?)");
$stmt->bind_param("issss", $id, $groupe, $dat, $nom1, $presence);
foreach ($_POST['id'] as $i => $id) {
$nom1 = trim($_POST['nom1'][$i];
$presence = $_POST['presence'][$i];
$stmt->execute();
}
I assume $rapport_id in your code should be $id.

Related

Insert data from while loop into a table with php

I'm creating a form using HTML and PHP. I have created a form which I want to submit and save that data in database.
I'm trying to submit a form with data that comes from a while loop. All input values are getting generated by while loop.
The code looks like this.
<table width="1348" border="0" class="table table-striped" >
<tr>
<td width="106"> </td>
<td width="332"><strong>Product Code</strong></td>
<td width="375"><strong>Product Name</strong></td>
<td width="211"><strong>QTY</strong></td>
</tr>
<?php
$i = 0;
$rowset = mysql_query("select * from product_detail where productID='".$data['productCode']."'");
while($stuff = mysql_fetch_array($rowset)){
?>
<tr>
<td><input type="text" name="code[<?php echo $i?>]" value="<?php enter code hereecho $stuff['code'];?>"/></td>
<td><input type="text" name="name[<?php echo $i?>]" value="<?php echo $stuff['name'];?>" size="50"/></td>
<td><input type="text" name="qty[<?php echo $i?>]" value="<?php echo $stuff['qty'];?>" size="10"/></td>
</tr>
<?php $i++; }?>
<tr id="last">
</table>
<input type="submit" name="save id="save" class="btn btn-primary btn-lg"/>
This is the code to add the data to database.
$code=$_POST['code'.$i];
$name=$_POST['name'.$i];
$qty=$_POST['qty'.$i];
$query = mysqli_query($con,"insert into stock(productCode, productName, qty) values ('".$code."', '".$name."','".$qty."')") or die(mysqli_error($con));
First, use prepared statement with bind_param as your script is totally exposed to sql injection.
Second, you can add input type hidden for the number of rows
<form action="" method="POST">
<table width="1348" border="0" class="table table-striped" >
<tr>
<td width="106"> </td>
<td width="332"><strong>Product Code</strong></td>
<td width="375"><strong>Product Name</strong></td>
<td width="211"><strong>QTY</strong></td>
</tr>
<?php
$data['productCode'] = "1"; // sample data
$stmt = $con->prepare("SELECT * FROM product_detail WHERE productID = ?");
$stmt->bind_param("i", $data['productCode']);
$stmt->execute();
$result = $stmt->get_result();
$i = 0;
while($stuff = $result->fetch_assoc()) {
?>
<tr>
<td></td>
<td><input type="text" name="code[<?php echo $i; ?>]" value="<?php echo $stuff['code'];?>"/></td>
<td><input type="text" name="name[<?php echo $i; ?>]" value="<?php echo $stuff['name']; ?>" size="50" /></td>
<td><input type="text" name="qty[<?php echo $i; ?>]" value="<?php echo $stuff['qty']; ?>" size="10" /></td>
</tr>
<?php
$i++;
}
?>
<input type="hidden" name="count" value="<?php echo $i; ?>" />
<tr id="last">
</table>
<input type="submit" name="save" id="save" class="btn btn-primary btn-lg"/>
</form>
post count with the form
<?php
if (isset($_POST['save'])) {
$count = $_POST['count'];
for ($i = 0; $i < $count; $i++) {
$code = $_POST['code'][$i]; // check empty and check if interger
$name = $_POST['name'][$i]; // check empty and strip tags
$qty = $_POST['qty'][$i]; // check empty and check if interger
$stmt = $con->prepare("INSERT INTO stock (productCode, productName, qty) VALUES (?, ?, ?)");
$stmt->bind_param("iss",$code,$name,$qty);
$stmt->execute();
}
}
?>
You may also want to check if post values are empty with other necessary validation before insert
Since the table is dynamically filled, you need to use an array as the name attribute
<table>
<tr>
<th>Name</th>
<th>Present</th>
<th>Excused</th>
<th>Unexcused</th>
<th>Ext</th>
</tr>
<?php
$query = "select * from TbCard";
$sql = mysqli_query($connect, $query);
$count = 0;
while ($data = mysqli_fetch_array($sql)) {
?>
<tr>
<td>
<input name="tableRow[<?php echo $count; ?>]['dataName']" id='name' type='text' value="<?php echo $data['Name'];?>" readonly style='border:none;width:350px'></input>
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Present"> Present
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Excused"> Excused
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Unexcused"> Unexcused
</td>
</tr>;
<?php
$count++;
}
?>
</table>
The php would be something like this, assuming that the data has values in it:
$tableRow = $_POST['tableRow'];
foreach($tableRow as $row){
/* here insert data from post */
echo $row['dataName'].' '.$row['status'].'<br/>';
}
To see the content of the array, use print_r($tableRow)
in this case i use a name tableRow

MySQL Insert only last row with while loop

I have a while loop. It is within a form.I want to insert all rows from while loop when submitting submit button. Below is the code of while loop.
<form method="POST" action="insert.php" n>
<table>
<?php
$i =0;
$link = mysqli_connect('localhost', 'root', '', 'shibu');
$sql = "select `cus_id`, `mobile`, `date`, `time`,
sum(`d1` + `d2` + `d3`) as `credit`,
from `finale`;
$result=mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count == 0){
?>
<tr>
<th><?php echo 'No Records Founds!' .mysqli_error($link); ?></th>
</tr>
<?php
}else{
while($sql_result = mysqli_fetch_assoc($result)){
?>
<tr>
<td><?php echo $i += 1; ?></td>
<td><input type="text" name="cus_id" value="<?php echo $sql_result['cus_id']; ?>" ></td>
<td><input type="text" name="mobile" value="<?php echo $sql_result['mobile']; ?>" ></td>
<td><input type="text" name="date" value="<?php echo $sql_result['date']; ?>" ></td>
<td><input type="text" name="time" value="<?php echo $sql_result['time']; ?>"</td>
<td><input type="text" name="credit" value="<?php echo $sql_result['credit']; ?>"></td>
</tr>
<?php
}
}
?>
</table>
<input name="submit" type="submit" />
</form>
This is my insert query.
<?php
$link = mysqli_connect('localhost', 'root', '', 'shibu');
$stmt = mysqli_prepare($link, "INSERT INTO single
(`cus_id`, `mobile`, `date`, `time`, `credit`) VALUES (?,?,?,?,?)");
mysqli_stmt_bind_param($stmt, 'isssi', $cus_id, $mobile, $date, $time, $credit);
foreach ((array)$_POST['cus_id'] as $i => $cus_id) {
$mobile = $_POST['mobile'];
$date = $_POST['date'];
$time = $_POST['time'];
$credit = $_POST['credit'];
mysqli_stmt_execute($stmt);
}
if(!$stmt){
echo "error". mysqli_error($link);
}
My problem is when I enter submit button, only last row enters not the whole rows.
I need your help heartily.
In your html code you need to have input names defined as array.
Like
<td><input type="text" name="cus_id[]" value="<?php echo $sql_result['cus_id']; ?>" ></td>
<td><input type="text" name="mobile[]" value="<?php echo $sql_result['mobile']; ?>" ></td>
<td><input type="text" name="date[]" value="<?php echo $sql_result['date']; ?>" ></td>
<td><input type="text" name="time[]" value="<?php echo $sql_result['time']; ?>"</td>
<td><input type="text" name="credit[]" value="<?php echo $sql_result['credit']; ?>"></td>
And while using them in php you need to loop them and run insert query
foreach ($_POST['cus_id'] as $i => $value) {
$cus_id = $_POST['cus_id'][$i];
$mobile = $_POST['mobile'][$i];
$date = $_POST['date'][$i];
$time = $_POST['time'][$i];
$credit = $_POST['credit'][$i];
// Yourinsert query
}
Please move your
mysqli_stmt_bind_param
line into foreach loop, just above
mysqli_stmt_execute
line.

Undefined Index & Update Query

I am trying to update mysql data from user input displayed on a table, i have used the following code, even though the name is set and the value is set when i click update the code states "Undefined index: LHA" but as you can see i have declared this along with Work_date, LHA, AAS, LSA, AAH (the fields throwing the undefiend index errors) I also want the unefcted data to remain the same in the mysql database as apposed to settting it to blank! This is the HTML (A while statement to fetch the data to populate the value fields in the html table)
while($row = $sth->fetch()) { ?>
<form action='../action.php' method='post'>
<tr>
<td> <?php echo $row['Name'] ?></td>
<td> <input name='car' id='car' value="vv1"><br/><br/></td>
<td> <select name='Night' id='Night'><option selected='selected' value='no'>No</option><option value='Yes'>Yes</option></select> <br/><br/></td>
<td> <input class='text' name="Siteid" type="text" value="<?php echo $row['Workbook ID']; ?>" /> <br/><br/></td>
<td> <input class='datepicker' name="Work_date" type="text" value="<?php echo date('l, F d, Y', strtotime($row['Work Date'])) ?>" placeholder="Select Date!"/><br/><br/></td>
<td> <input class='timepicker' name="LHA" type="text" value="<?php echo $row['LHA'] ?>" /><br/><br/></td>
<td> <input class='timepicker' name="AAS" type="text" value="<?php echo $row['AAS'] ?>" /><br/><br/></td>
<td> <input class='timepicker' name="LSA" type="text" value="<?php echo $row['LS'] ?>" /><br/><br/></td>
<td> <input class='timepicker' name="AAH" type="text" value="<?php echo $row['AAH'] ?>" /><br/><br/></td>
<td> <input name="Bonus" type="text" value="<?php echo $row['Bonus']; ?>" /> <br/><br/></td>
<td> <input name="Work_Completed" type="text" value="<?php echo $row['Work Completed']; ?>" /> <br/><br/></td>
<td> <input name="BH" type="text" value="<?php echo $row['Hours']; ?>" /><br/><br/></td>
<input type='hidden' name='PID' value="<?php echo $row['PID'];?>" />
<td><input type='submit' name='delete_timesheet' value='delete' /></td>
<td><input type='submit' class='btn btn-default' name='update_timesheet' value='Update' /></td>
</tr>
</form>
<?php
}
Just to mention my query and field settings work perfectly on XAMPP but not when online, this is my PHP
if(isset($_POST['update_timesheet'])) {
$a = $_POST['car'];
$b = $_POST['Night'];
$c = $_POST['Siteid'];
$d = $_POST['Work_date'];
$e = $_POST['LHA'];
$f = $_POST['AAS'];
$g = $_POST['LSA'];
$h = $_POST['AAH'];
$i = $_POST['Bonus'];
$j = $_POST['BH'];
$l = $_POST['PID'];
$Paid = create_paid($e, $f, $g, $h);
$stmt = "UPDATE data SET Car = ?, Night = ?, `Workbook ID` = ?, `Work Date` = ?, LHA = ?, AAS = ? , LS = ? , AAH = ? , Bonus = ?, `Work Completed` = ?, Hours = ? WHERE PID = ? ";
$y = $pdo->prepare($stmt);
$y->execute(array($a,$b, $c, $d, $e, $f, $g, $h, $i, $j, $Paid, $l));
header('Location: ' . $_SERVER['HTTP_REFERER']);
}

Want to update multiple records using checkboxes and save button

I am searching some records using two text boxes and then updating the selected records in database. i am able to see the value row id of the selected checkbox but when i want to get the value for updation in database it gives 0, i.e showing no record in array
Here is my code
if($_POST["search"])
{
$nitnumber = $_POST["nitnumber"];
$workno = $_POST["workno"];
$query = "select * from print where nit = $nitnumber and work = $work";
$result = mysql_query($query) or die ("<font color =red>NIT Number and/or Work Number is Missing</font>");
$count = mysql_num_rows($result);
if($count == 0)
echo "<font color=red>Record not found</font>";
else
{
while($record = mysql_fetch_assoc($result))
{
?>
<tr class="odd">
<td><div align="center"><?php echo $record['a']; ?></div></td>
<td><div align="center"><?php echo $record['b']; ?></div></td>
<td><div align="left"><?php echo $record['c']; ?></div></td>
<td> <div align="left">
<?php
enter code hereecho $record["d"];
?>
</td>
<td>
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>">
<?php echo $record["id"];?>
</td>
<?php } } }?>
<tr>
<td colspan="5" align="right"> <input type="submit" value="Save" name="save"> </td>
</tr>
<?php
if ($_POST['save'])
{
$num_chkboxes=count($_POST['checkbox']);
for($i=0; $i<$num_chkboxes; $i++){
$complete = intval($checkbox[$i]);
echo $complete;
var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
//$Result1 = mysql_query($updateSQL, $FamilyOrganizer) or die(mysql_error());
}
}
?>
<?php
if ($_POST['save'])
{
$checkbox1 = $_POST['chk1'];
$selected_checkbox = "";
foreach ($checkbox1 as $checkbox1)
{
$selected_checkbox .= $checkbox1 . ", ";
}
$selected_checkbox = substr($selected_checkbox, 0, -2);
$updateSQL = "" // your update query here
}
?>
<input type="checkbox" name="chk1[]" value=""> // take checkboxes like this
First, the problem started when you fill the values of the checkboxes:
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>" />
you must gave them the value like
value="<?php echo $record['id'] ?>"
Second, you don't get the values of the checkboxes as you should:
for($i = 0; $i < count($_POST['checkbox']); $i++){
$complete = intval($_POST['checkbox'][$i]);
//echo $complete;
//var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
}
Another thing you should take care about is the assigning of the elements ids:
id="checkbox[]"
you must give unique ids for each element:
id="checkbox-1"
id="checkbox-2"

saving data from an array without submitting any form 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...

Categories