MySQL Insert only last row with while loop - php

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.

Related

sending while loop radio button data to database using 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.

How to disable button when returned books is equal with original books volume?

I am making a book management system.I have a return button ,with that button user can return books.
Here is my release-books.php:
<?php
$sql_select = "SELECT * FROM carti ORDER BY titlu";
$rezultat = mysqli_query($conn, $sql_select);
if (mysqli_num_rows($rezultat) > 0) {
while ($row = mysqli_fetch_assoc($rezultat)) {
$disabled = $row['stoc'] > 0 ? "" : "disabled"; ?>
<tr><td><input type="submit" name="id" value="<?php echo $row['idCarte']; ?>" <?php echo $disabled; ?> formaction="imprumutare.php"></input></td>
<td><input type="submit" name="returnare" value="<?php echo $row['idCarte']; ?>" formaction="returnare_carte.php"></input>
</td>
<td><input type="text" name="nume" value="<?php echo $row['titlu']; ?>" ></input></td>
<td><input type="text" name="" value="<?php echo $row['autor']; ?>"></input></td>
<td><input type="text" name="" value="<?php echo $row['editura']; ?>"></input></td>
<td><input type="text" name="" value="<?php echo $row['categorie']; ?>"></input></td>
<td><input type="text" name="" value="<?php echo $row['data_adaugarii']; ?>"></input></td>
<td><input type="text" name="" value="<?php echo $row['stoc']; ?>"></input></td>
</tr>
<?php
}
}
?>
And here is my borrowing.php
include('conexiune.php');
//sfarsit if
//Imprumutare
if (isset($_POST['id'])) {
$identificator = $_POST['id'];
$carte_nume = $_POST['nume'];
$current_date = date('y:m:d');
$current_date_plus_14days = date('y:m:d', strtotime("+14 days"));
$nume_carte = $_POST['nume'];
$insert_in_imprumuturi = "INSERT INTO imprumuturi(idc,nume_carte,data,termen_returnare,carti_imprumutate) VALUES('$identificator','$carte_nume','$current_date','$current_date_plus_14days','1')";
mysqli_query($conn, $insert_in_imprumuturi) or die(mysqli_error($conn));
$sql_rezervare = "UPDATE carti SET stoc=stoc-1 WHERE iDCarte='$identificator' ";
if (mysqli_query($conn, $sql_rezervare)) {
header('Refresh:0,url=emitere_carti.php');
} else {
die(mysqli_error($conn));
}
}
But I do not know how to disable the return button when the returned books volume is equal or greater that the originial volume
Can somone help me?
Check If your books volume is equal or greater than original volume, if it is. Use PHP echo to disable the Return Button.
<button type="submit" name="return"
<?php
if($returned_books_volume >= $original_books_volume){
echo 'disabled';
}
?>
>Return</button>

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

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.

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

Categories