Insert data from while loop into a table with php - 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

Related

Html table only last row instead of all rows is inserting in mysql database

I am implementing clothing shopping website. I am having a problem when I place order only last row item from the shopping cart HTML table is inserted into the database and not all rows. I want that when I click on place order button all rows values should be inserted in the database. so that customers all selected items in the shopping cart should be placed for order.
Here is the code,
<table align="center" >
<thead>
<tr >
<th>Product</th>
<th>Price</th>
<th>QTY</th>
<th>SubTotal</th>
</tr>
</thead>
<?php
if (!empty($_SESSION["shopping_cart"]))
{
$total=0;
foreach ($_SESSION["shopping_cart"] as $keys => $values) {
?>
<tr>
<td>
<p>Product Code:<?php echo $values["item_id"]; ?> <br/>
<?php echo $values["item_gender"]; ?><br/>
<?php echo $values["item_description"]; ?> </p></td>
<td>PKR
<input type="number" name="price1" id="price1" value="<?php echo $values["item_price"];?>" readonly ></td>
<td><input type="number" name="qty[<?php echo $values["item_id"]; ?>]" id="qty" value="<?php echo $values["item_quantity"];?>"></td>
<input type="hidden" name="qty" value="<?php echo $values["item_quantity"];?>" >
<td >PKR<input type="number" name="total" id="total" value="<?php echo ($values["item_quantity"] * $values["item_price"]) ?>"readonly></td>
</tr>
<?php
$total=$total+($values['item_quantity']*$values["item_price"]);
/* $total=$total+$values["item_price"]; */
}
} ?>
</table> <br/><br/>
<button type="submit" name="submit" class="btn btn-primary btn-lg">Place Order</button>
here is php code,
if (isset($_POST['submit']))
{
$product_code = $_POST['ID'];
$price = $_POST['grandtotal'];
$quantity = $_POST['qty'];
$description = $_POST['description'];
$email=$_SESSION["email"];
$con=mysql_connect("localhost", "root", "");
mysql_select_db("login",$con);
$qry="INSERT INTO order ( order_description , product_code, order_quantity, order_price, customer_name, email, customer_id) VALUES ('$description', '$product_code', '$quantity', '$price', (SELECT name from users where email='$email'), '$email', (SELECT user_id from users where email='$email') ) ";
$result=mysql_query($qry,$con);
if($result)
{
echo '<script>alert("Your order has been placed")</script>';
echo '<script>window.location="portfolionew.php"</script>';
} else {
die("Error While Adding Stock ! Please Try Again .");
}
}
<table align="center">
<thead>
<tr >
<th>Product</th>
<th>Price</th>
<th>QTY</th>
<th>SubTotal</th>
</tr>
</thead>
<?php
if (!empty($_SESSION["shopping_cart"]))
{
$total=0;
$i = 1;
foreach ($_SESSION["shopping_cart"] as $keys => $values) {
?>
<tr>
<td style=" text-align: left;" >
<p style="margin-top: -120px; margin-left: 150px;">Product Code:<?php echo $values["item_id"]; ?> <br/>
<?php echo $values["item_gender"]; ?><br/>
<?php echo $values["item_description"]; ?> </p></td>
<td style="text-align: left; width: 80px;">PKR<br/>
<input style="width: 70px;" type="number" name="price<?= $i; ?>" id="price<?= $i; ?>" value="<?php echo $values["item_price"];?>" readonly ></td>
<td><input type="number" name="qty_<?= $i; ?>" id="qty_<?= $i; ?>" value="<?php echo $values["item_quantity"];?>"></td>
<td style="text-align: left; width: 80px;"> <b>PKR</b>
<br/> <input style="width: 70px; " type="number" name="total" id="total" value="<?php echo ($values["item_quantity"] * $values["item_price"]) ?>"readonly></td>
</tr>
<?php
$total=$total+($values['item_quantity']*$values["item_price"]);
$i++;
/* $total=$total+$values["item_price"]; */
}
} ?>
<input hidden="iTotalProducts" value="<?php echo $i; ?>" name="product_count">
</table> <br/><br/>
<button type="submit" name="submit" class="btn btn-primary btn-lg">Place Order</button>
//here is php code,
if (isset($_POST['submit']))
{
$product_code = $_POST['ID'];
$price = $_POST['grandtotal'];
$quantity = $_POST['qty'];
$description = $_POST['description'];
$email=$_SESSION["email"];
$con=mysql_connect("localhost", "root", "");
mysql_select_db("login",$con);
$cnt = $_POST["iTotalProducts"];
for($i = 1; $i <= $cnt; $i++) {
// here you can write your insert code
}
if($result)
{
echo '<script>alert("Your order has been placed")</script>';
echo '<script>window.location="portfolionew.php"</script>';
} else {
die("Error While Adding Stock ! Please Try Again .");
}
} `enter code here`

How to insert multiple row to new table using single submit button

I am try to inset multiple rows to new table fetched from other table, but problem is that only last single row is being inserted and no other now is getting insert, so please tell the issue where i am lacking
<?php
error_reporting(1);
session_start();
$s=$_SESSION['username'];
//connect database
$con=mysql_connect("localhost","root","") or die(mysql_error());
// select database
mysql_select_db("education",$con);
$date= date("Y/m/d");
//select all values from empInfo table
$data="SELECT * FROM student";
$val=mysql_query($data);
?>
<html>
<body>
<table>
</table>
<form action="submit.php" method="post" >
<table>
<tr>
<th>Teacher name</th>
<th>Date</th>
<th>Roll No</th>
<th>Student name</th>
<th>Father name</th>
<th>Addhaar No</th>
<th>Status(P)</th>
<th>Status(A)</th>
<th>Status(L)</th>
</tr>
<?php while($r=mysql_fetch_array($val))
{?>
<tr style="border:2px solid black;">
<td><input type="text" name="teacher" value="
<?php echo $s; ?>"></td>
<td><input type="text" name="date" value="
<?php echo $date; ?>"></td>
<td ><input name="roll_no" value="
<?php echo $r['roll_no']; ?>">
</td>
<td><input name="student_name" value="
<?php echo $r['student_name'] ?>">
</td>
<td><input name="father_name" value="
<?php echo $r['father_name'] ?>">
</td>
<td>
<input name="addhaar_no" value="
<?php echo $r['addhaar_no'] ?>">
</td>
<td>
<input type="checkbox" value="present" name="status"> Present
</td>
<td>
<input type="checkbox" name="status" value="absent">Absent
</td>
<td>
<input type="checkbox" name="status" value="leave">Leave
</td>
</tr>
</table>
<?
}
?>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
submit.php -
<?php
error_reporting(1);
$con=mysql_connect("localhost","root","") or die(mysql_error());
// select database
mysql_select_db("education",$con);
//get data from html form
$roll_no=$_POST['roll_no'];
$student_name=$_POST['student_name'];
$father_name=$_POST['father_name'];
$addhaar_no=$_POST['addhaar_no'];
$status=$_POST['status'];
//Insert values in empInfo table with column name
$query="INSERT INTO attandance
VALUES ('', '$roll_no','$student_name','$father_name','$addhaar_no','$status'),
VALUES ('', '$roll_no','$student_name','$father_name','$addhaar_no','$status')";
echo $query;
die();
mysql_query($query);
?>
page
You need to have unique name for each fields. What you can do is have a counter in loop and add it the names of the fields to make it unique.
Sample:
$ctr = 0;
while($r=mysql_fetch_array($val)){
echo "<input type="text" name='teacher_".$ctr."'>";
$ctr++;
}
Or make the names array, and loop through the values in saving the data.
while($r=mysql_fetch_array($val)){
echo "<input type="text" name='teacher[]'>";
}
I think you should study PHP a bit more... As i can see in your code, you haven't understood fundamentals of PHP.
1: Normally, you won't mix up HTML and PHP like you did in your first code. Its just confusing and really annoying to read the code later.
2: When you post your form, for example the variable $_POST['student_name']; will just contain the value of the last row (your problem). So, why? Because you can't assign more than one value to a variable. Or at least, not the way you tried it. Array would be a good keywoard for this problem.
3: Please check your SQL syntax... Thats why i'm saying you haven't understand fundamentals... http://www.w3schools.com/sql/sql_insert.asp
Why you're repeating your values? You think the second time the variables will contain the values of the next row? Thats just false. A Variable contains everytime the same value, as long as you don't assign a new value to it.
4: mysql is depracted. Use mysqli or PDO instead.
My tip: You need to have unique input names. Just take a look at PHP, how for/while loops work, study a bit more and try it again. It's not difficult to solve, but i think you'll learn a lot more if we don't give you the direct solution.
Now mysql is depracted. So, you can use mysqli or PDO instead.
I can use now PDO. Please follow bellow code carefully:
<?php
$user = 'root';
$pass = '';
$dbh = new PDO('mysql:host=localhost;dbname=education', $user, $pass);
try {
$select = $dbh->query('SELECT * from student');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
<html>
<body>
<form action="submit.php" method="post" >
<table>
<tr>
<th>Teacher name</th>
<th>Date</th>
<th>Roll No</th>
<th>Student name</th>
<th>Father name</th>
<th>Addhaar No</th>
<th>Status(P)</th>
<th>Status(A)</th>
<th>Status(L)</th>
</tr>
<?php
foreach($select as $val) {
?>
<tr style="border:2px solid black;">
<td><input type="text" name="teacher" value="<?php echo $s; ?>"></td>
<td><input type="text" name="date" value="<?php echo $date; ?>"></td>
<td><input name="roll_no" value="<?php echo $r['roll_no']; ?>"></td>
<td><input name="student_name" value="<?php echo $r['student_name'] ?>"></td>
<td><input name="father_name" value="<?php echo $r['father_name'] ?>"></td>
<td><input name="addhaar_no" value="<?php echo $r['addhaar_no'] ?>"></td>
<td><input type="checkbox" value="present" name="status"> Present</td>
<td><input type="checkbox" name="status" value="absent">Absent</td>
<td><input type="checkbox" name="status" value="leave">Leave</td>
</tr>
<?php
}
?>
</table>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
For submit.php code bellow
<?php
$user = 'root';
$pass = '';
$dbh = new PDO('mysql:host=localhost;dbname=education', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO attandance (roll_no, student_name, father_name, addhaar_no, status) VALUES (?, ?, ?, ?, ?)");
$stmt->bindParam(1, $roll_no);
$stmt->bindParam(2, $student_name);
$stmt->bindParam(2, $father_name);
$stmt->bindParam(2, $addhaar_no);
$stmt->bindParam(2, $status);
//if you insert 2 time then
for($x=0; $x<2; $x++) {
$roll_no = $_POST['roll_no'];
$student_name = $_POST['student_name'];
$father_name = $_POST['father_name'];
$addhaar_no = $_POST['addhaar_no'];
$status = $_POST['status'];
$stmt->execute();
}
?>

Display all rows and update all rows by a submit

I want to display all rows by a php query and update all by a submit button in sql. I this way below a can display all row and update particular row by its own submit button. But I want to update all by a single submit button.
So for do it, I thank, I want to loop for update. But I cannot understand how to do it in this case.
Here is my code:
<?php
include_once('../db.php');
global $db;
$result = mysqli_query($dbh,"SELECT * FROM ppad");
if(!$result) {
die("Database query failed: " . mysqli_error());
}
while($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$name=$row['name'];
$date=$row['date'];
$title=$row['title'];
$Detail=$row['Detail'];
echo '<form action="padSproccess.php" method="POST">
<table width="100%" border="1">
<tr>
<td width="10%">Date</td>
<td width="14%">Time</td>
<td width="20%">Name(url)</td>
<td width="30%">Detail</td>
</tr>
<tr>
<td width="10%"><input type="text" name="date" maxlength="2" value="'.$date.'"></td>
<td width="14%"><input type="text" name="title" maxlength="50" value="'.$title.'"></td>
<td width="20%"><input type="text" name="name" maxlength="50" value="'.$name.'"></td>
<td width="30%"><input type="text" name="Detail" maxlength="100" value="'.$Detail.'"></td>
<input type="hidden" name="id" value="'.$id.'">
</tr>
</table>
<input type="submit" name="submit" id="submit" value="Submit">
</form>';}
?>
padSproccess.php
include("../db.php");
global $db;
if(isset($_POST['submit'])){
$date = mysqli_real_escape_string($dbh,$_POST['date']);
$title = mysqli_real_escape_string($dbh,$_POST['title']);
$name = mysqli_real_escape_string($dbh,$_POST['name']);
$Detail = mysqli_real_escape_string($dbh,$_POST['Detail']);
$id = mysqli_real_escape_string($dbh,$_POST['id']);
// update data in mysql database
$update = mysqli_query($dbh,"UPDATE ppad SET date='$date', month='$month', name='$name', Detail='$Detail' WHERE id = '$id'");
// if successfully updated.
}
For this you need to update your code into
<?php
include_once('../db.php');
global $db;
$result = mysqli_query($dbh,"SELECT * FROM ppad");
if(!$result) {
die("Database query failed: " . mysqli_error());
}?>
<form action="padSproccess.php" method="POST">
<table width="100%" border="1">
<tr>
<td width="10%">Date</td>
<td width="14%">Time</td>
<td width="20%">Name(url)</td>
<td width="30%">Detail</td>
</tr>
<?php
while($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$name=$row['name'];
$date=$row['date'];
$title=$row['title'];
$Detail=$row['Detail'];
echo '<tr>
<td width="10%"><input type="text" name="date[]" maxlength="2" value="'.$date.'"></td>
<td width="14%"><input type="text" name="title[]" maxlength="50" value="'.$title.'"></td>
<td width="20%"><input type="text" name="name[]" maxlength="50" value="'.$name.'"></td>
<td width="30%"><input type="text" name="Detail[]" maxlength="100" value="'.$Detail.'"></td>
<input type="hidden" name="id[]" value="'.$id.'">
</tr>';
}?>
</table>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
Now within your padSproccess.php you'll receive an array of results within your variables which'll be updated using foreach loop
What you need to do first is have an overall form, not a form for each (unless you want to throw in javascript to fire off ajax calls). So what you'll need to do is make sure each row can be associated with a specific id:
<?php
include_once '../db.php';
$result = mysqli_query($dbh, "SELECT * FROM ppad");
if(!$result) {
die("Database query failed: " . mysqli_error());
}
?>
<form action="padSproccess.php" method="POST">
<table width="100%" border="1">
<thead>
<tr>
<td width="10%">Date</td>
<td width="14%">Time</td>
<td width="20%">Name(url)</td>
<td width="30%">Detail</td>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$name = $row['name'];
$date = $row['date'];
$title = $row['title'];
$Detail = $row['Detail'];
echo '
<tr>
<td width="10%"><input type="text" name="date[' . $id . ']" maxlength="2" value="'.$date.'"></td>
<td width="14%"><input type="text" name="title[' . $id . ']" maxlength="50" value="'.$title.'"></td>
<td width="20%"><input type="text" name="name[' . $id . ']" maxlength="50" value="'.$name.'"></td>
<td width="30%"><input type="text" name="Detail[' . $id . ']" maxlength="100" value="'.$Detail.'"></td>
</tr>
';
}
?>
</tbody>
</table>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
Then in padSproccess.php you'll receive an array of names, dates, titles and Details, each one keyed by the ID of the row. So that'll change to something like this:
<?php
include "../db.php";
if(isset($_POST['submit'])){
$ids = array_keys($_POST['name']);
foreach ($ids as $id) {
$date = mysqli_real_escape_string($dbh,$_POST['date'][$id]);
$title = mysqli_real_escape_string($dbh,$_POST['title'][$id]);
$name = mysqli_real_escape_string($dbh,$_POST['name'][$id]);
$Detail = mysqli_real_escape_string($dbh,$_POST['Detail'][$id]);
$id = mysqli_real_escape_string($id);
// update data in mysql database
$update = mysqli_query($dbh,"UPDATE ppad SET date='$date', month='$month', name='$name', Detail='$Detail' WHERE id = '$id'");
}
// if successfully updated.
}
Try this. Of course for the database I've not started and it is possible errors.
<?php
include_once('../db.php');
global $db;
$result = mysqli_query($dbh,"SELECT * FROM ppad");
if(!$result) {
die("Database query failed: " . mysqli_error());
}
?>
<form action="padSproccess.php" method="POST">
<?php
while($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$name=$row['name'];
$date=$row['date'];
$title=$row['title'];
$Detail=$row['Detail'];
echo '
<table width="100%" border="1">
<tr>
<td width="10%">Date</td>
<td width="14%">Time</td>
<td width="20%">Name(url)</td>
<td width="30%">Detail</td>
</tr>
<tr>
<td width="10%"><input type="text" name="ar['.$id.'][date]" maxlength="2" value="'.$date.'"></td>
<td width="14%"><input type="text" name="ar['.$id.'][title]" maxlength="50" value="'.$title.'"></td>
<td width="20%"><input type="text" name="ar['.$id.'][name]" maxlength="50" value="'.$name.'"></td>
<td width="30%"><input type="text" name="ar['.$id.'][Detail]" maxlength="100" value="'.$Detail.'"></td>
</tr>
</table>
';}
?>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
<?php
include("../db.php");
global $db;
if(isset($_POST['submit'])){
foreach($_POST['ar'] as $id=>$dat){
$date = mysqli_real_escape_string($dbh,$dat['date']);
$title = mysqli_real_escape_string($dbh,$dat['title']);
$name = mysqli_real_escape_string($dbh,$dat['name']);
$Detail = mysqli_real_escape_string($dbh,$dat['Detail']);
$id = mysqli_real_escape_string($dbh,$id]);
// update data in mysql database
$update = mysqli_query($dbh,"UPDATE ppad SET date='$date', month='$month', name='$name', Detail='$Detail' WHERE id = '$id'");
}
// if successfully updated.
}
?>

Php form update in update the form

I am running while loop and fetch 3 records from database. and then update it on same page. Every record have submit button. But after edit when i submit the form it catchs the values of last record only and update other rows with the last record values. Please if somebody help me out i'll be very thankful. Remember it catches the exact (id) but the other parameters are only of last row.
<form method="post" action="">
<table width="700" border="1">
<tr><th><?php echo $_SESSION['teamtwo']; ?></th></tr>
<tr>
<th>Player Name</th>
<th>Runs</th>
<th>Edit</th>
<th>Save</th>
</tr>
<?php
$team = new DBConnection();
$condition = "WHERE teamname = '".$_SESSION['teamtwo']."' and datecreated = CURDATE()";
$sel_player = $team->SelectRecord(array("*"),"`match`","$condition");
//$sel_player = mysql_query("SELECT * FROM `match` WHERE teamname = '$team1' and datecreated = CURDATE()") or die(mysql_error());
while($get_player = mysql_fetch_array($sel_player))
{
$totalruns = $get_player['runs_bat'];
$totalballs = $get_player['ball_bat'];
#$strike = $totalruns / $totalballs * 100;
?>
<tr>
<td><input type="text" name="player_name" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
<td><button>Edit</button></td>
<td><input type="submit" value="Save" name="team" /></td>
</tr>
<?php
} ?>
</table>
</form>
<?php } ?>
</div>
</div>
</body>
</html>
<?php
if(isset($_POST['team'])){
$runs = $_POST['runs'];
$balls = $_POST['ball'];
$object = new DBConnection();
$arr_Field=array("runs_bat","ball_bat","player_status","how_out","opposite_bowl","opposite_player","sr","overs","bowl_ball","runs_ball","extra","madien");
$arr_Values=array("$runs","$balls","$status","$how_out","$opposite_bowler","$opposite_player","$sr","$over","$bowls","$score","$extra","$madien");
$condition = "WHERE id = '".$_REQUEST['player']."'";
//echo $_REQUEST['player'];
//echo $runs.$balls;
$object->UpdateRecord("`match`",$arr_Field,$arr_Values,"$condition") or die(mysql_error());
//header("Location:extra.php?update");
}
the problem is you are having one form and when you submit the form it will submit the last rows values because you are having same name for all 3 rows inside 1 form.
Solution:-
Create form element inside the while loop and close it inside the while loop itself . Like this you will have 3 forms each for 3 rows.
Code Example:-
while($get_player = mysql_fetch_array($sel_player))
{
$totalruns = $get_player['runs_bat'];
$totalballs = $get_player['ball_bat'];
#$strike = $totalruns / $totalballs * 100;
?>
<form>
<tr>
<td><input type="text" name="player_name" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
<td><button>Edit</button></td>
<td><input type="submit" value="Save" name="team" /></td>
</tr>
</form>
<?php
} ?>
1.
you need to make input array in while because name attribute is overwriting in loop
<td><input type="text" name="player_name[<?php echo $get_player['id']?>]" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs[<?php echo $get_player['id']?>]" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
2.
you have all text boxes mean if press submit button of one row, then also you will get all textboxes as php side so make hidden variable in form to get which button clicked
//write javascript in your page
<script>
function setPlayerId(id) {
document.getElementById('playerid').value=id;
}
</script>
//take hidden field into form
<input type='hidden' name='playerid' value='0'>
//write down onlick button event
<input type="submit" value="Save" name="team" onClick="setPlayerId('<?php <?php echo $get_player['id']?>?>')"/>
3.
Now in php you will get that as below
echo $_POST['player_name'][$_POST['playerid']];
// same way you can do your insert or update.
this code must work
<form method="post" action="">
<table width="700" border="1">
<tr><th><?php echo $_SESSION['teamtwo']; ?></th></tr>
<tr>
<th>Player Name</th>
<th>Runs</th>
<th>Edit</th>
<th>Save</th>
</tr>
<?php
$team = new DBConnection();
$condition = "WHERE teamname = '".$_SESSION['teamtwo']."' and datecreated = CURDATE()";
$sel_player = $team->SelectRecord(array("*"),"`match`","$condition");
//$sel_player = mysql_query("SELECT * FROM `match` WHERE teamname = '$team1' and datecreated = CURDATE()") or die(mysql_error());
while($get_player = mysql_fetch_array($sel_player))
{
$totalruns = $get_player['runs_bat'];
$totalballs = $get_player['ball_bat'];
#$strike = $totalruns / $totalballs * 100;
?>
<tr>
<td><input type="text" name="player_name" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs<?=$get_player['id']?>" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
// you didnt write this i added
<input type="text" name="ball<?=$get_player['id']?>" value="<?php echo $get_player['ball_bat']; ?>" size="1" />
<td><button>Edit</button></td>
<td><input type="submit" value="Save" name="team" /></td>
</tr>
<?php
} ?>
</table>
</form>
<?php } ?>
</div>
</div>
</body>
</html>
<?php
if(isset($_POST['team'])){
$runsname = 'runs'.$_GET['player'];
$ballsname = 'ball'.$_GET['player'];
$runs = $_POST[$runsname];
$balls = $_POST[$ballsname];
$object = new DBConnection();
$arr_Field=array("runs_bat","ball_bat","player_status","how_out","opposite_bowl","opposite_player","sr","overs","bowl_ball","runs_ball","extra","madien");
$arr_Values=array("$runs","$balls","$status","$how_out","$opposite_bowler","$opposite_player","$sr","$over","$bowls","$score","$extra","$madien");
$condition = "WHERE id = '".$_REQUEST['player']."'";
//echo $_REQUEST['player'];
//echo $runs.$balls;
$object->UpdateRecord("`match`",$arr_Field,$arr_Values,"$condition") or die(mysql_error());
//header("Location:extra.php?update");
}

php $_get variable gone after submitting form

my problem goes like this:
my home page has tables with rows pulled from the database (while loops)
each row has a - cell in which he can add an event to that specific row
in order to do that i send the row id as a $_GET variable from the home page table
and in the "add event" page i store it as a variable
but when i submit my addevent form without filling it properly (as i coded) it simply refreshes the form only without the row id in the url therefor also the query i do in the beginning of the page for pulling the row data can no longer execute and that pops a PHP error
for the id variable which i sign it the $_GET and the query (mysql fetch array).
also of course all the data which i display in the form from that query is gone.
any suggestions on how to approach this ? thanks in advance, Regards.
EDIT:** kill the new guy! -Sorry i guess
home page where i send the id :
$sql = "SELECT * FROM alarms WHERE alarmstatus = 'OFF' and starttime='::' ORDER BY clientid ASC";
$query = mysql_query($sql);
echo "<table cellpadding='1px' border='1px' bordercolor='#0066FF' cellspacing='0'>
<form action='hpage.php' method='get'>";
while($fetch = mysql_fetch_array($query)) {
echo "<tr>
<td>
".$fetch['clientid']."</td>
<td>".$fetch['controller']."</td>
<td>".$fetch['typeid']."</td>
<td style='color: red'>".$fetch['alarmstatus']."</td>
<td>".$fetch['starttime']."</td>
<td>".$fetch['endtime']."</td>
<td><a href='includes/editalarm.php?id=".$fetch['id']."'>Edit</a></td>
<td><a href='includes/addevent.php?id=".$fetch['id']."'>Add event</a></td>
<td><a href='includes/deletealarm.php?id=".$fetch['id']."'>Delete</a></td>
</tr>";
}
the add event where i get the variable and make the query:
$alarmid = $_GET['id'];
$sql = "SELECT * FROM alarms WHERE id=".$alarmid;
$query = mysql_query($sql);
$fetch = mysql_fetch_array($query);
?>
the form:
<table cellpadding="2px" cellspacing="0" >
<form action="addevent.php" method="post">
<tr>
<td>סניף:</td>
<td><input style="width:200px; background-color: #d6d6d6;" readonly name="client" value="<?php echo $fetch['clientid']; ?>" /></td>
</tr>
<tr>
<td>בקר:</td>
<td><input style="width:200px; background-color: #d6d6d6;" readonly name="controller" value="<?php echo $fetch['controller']; ?>" /></td>
</tr>
<tr>
<td>אזעקה:</td>
<td><input style="width:200px; background-color: #d6d6d6;" readonly name="controller" value="<?php echo $fetch['typeid']; ?>" /></td>
</tr>
<tr>
<td>מוקדן:</td>
<td>
<?php
$sql = "SELECT * FROM users WHERE privilege = '2'";
$query = mysql_query($sql);
echo "<select name='user' style='width:207px;'>";
echo "<option>..</option>";
while ($fetch2 = mysql_fetch_array($query)){
echo "<option>".$fetch2['username']."</option>";
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td>איש קשר:</td>
<td><input type="text" name="contact" /></td>
</tr>
<tr>
<td>הודעה:</td>
<td><input type="text" style="width:200px; height:100px" name="message" /></td>
</tr>
<tr>
<td>תשובה:</td>
<td><input type="text" style="width:200px; height:100px" name="answer" /></td>
</tr>
<tr>
<td>שעה:</td>
<td>
<select name="eventhour">
<option value ="default"></option>
<?php
for($i = 0; $i<60; $i++){
$value = $i;
if($i<=9){
$value= "0".$i;
}
echo "<option>".$value."</option>";
}
?>
</select>
<select name="eventminute">
<option value ="default"></option>
<?php
for($i = 0; $i<24; $i++){
$value = $i;
if($i<=9){
$value= "0".$i;
}
echo "<option>".$value."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" name="save" value="שמור" />
<input type="submit" name="cancell" value="בטל" />
</td>
<td></td>
</tr>
</form>
Your form action is POST. If you change that to GET then you will have the form as $_GET.

Categories