I know there is a simpler way to do this. What I'm trying to do is group fields by number and use isset to test if $_POST['item#'] value is empty. If that item# is not empty, I want to send corresponding color, quantity, and price. If there is more than one item submitted, I want to send multiples.
Here are my post variables:
$item1 = $_POST['item1'];
$color1 = $_POST['color1'];
$quantity1 = $_POST['quantity1'];
$price1 = $_POST['price1'];
$item2 = $_POST['item2'];
$color2 = $_POST['color2'];
$quantity2 = $_POST['quantity2'];
$price2 = $_POST['price2'];
$item3 = $_POST['item3'];
$color3 = $_POST['color3'];
$quantity3 = $_POST['quantity3'];
$price3 = $_POST['price3'];
$item4 = $_POST['item4'];
$color4 = $_POST['color4'];
$quantity4 = $_POST['quantity4'];
$price4 = $_POST['price4'];
$item5 = $_POST['item5'];
$color5 = $_POST['color5'];
$quantity5 = $_POST['quantity5'];
$price5 = $_POST['price5'];
$item6 = $_POST['item6'];
$color6 = $_POST['color6'];
$quantity6 = $_POST['quantity6'];
$price6 = $_POST['price6'];
$item7 = $_POST['item7'];
$color7 = $_POST['color7'];
$quantity7 = $_POST['quantity7'];
$price7 = $_POST['price7'];
$item8 = $_POST['item8'];
$color8 = $_POST['color8'];
$quantity8 = $_POST['quantity8'];
$price8 = $_POST['price8'];
I'm using isset to test if $_POST[] values are empty:
if( isset($_POST['item1']) )
{
$message = 'Item: '.$item1." \nColor: ".$color1." \nQuantity: ".$quantity1." \nPrice: ".$price1;
}
if( isset($_POST['item2']) )
{
$message = 'Item: '.$item2." \nColor: ".$color2." \nQuantity: ".$quantity2." \nPrice: ".$price2;
}
if( isset($_POST['item3']) )
{
$message = 'Item: '.$item3." \nColor: ".$color3." \nQuantity: ".$quantity3." \nPrice: ".$price3;
}
if( isset($_POST['item4']) )
{
$message = 'Item: '.$item4." \nColor: ".$color4." \nQuantity: ".$quantity4." \nPrice: ".$price4;
}
if( isset($_POST['item5']) )
{
$message = 'Item: '.$item5." \nColor: ".$color5." \nQuantity: ".$quantity5." \nPrice: ".$price5;
}
if( isset($_POST['item6']) )
{
$message = 'Item: '.$item6." \nColor: ".$color6." \nQuantity: ".$quantity6." \nPrice: ".$price6;
}
if( isset($_POST['item7']) )
{
$message = 'Item: '.$item7." \nColor: ".$color6." \nQuantity: ".$quantity7." \nPrice: ".$price7;
}
if( isset($_POST['item7']) )
{
$message = 'Item: '.$item8." \nColor: ".$color7." \nQuantity: ".$quantity8." \nPrice: ".$price8;
}
$items = $_POST['item'];
for ($i = 0; $i < count($items); $i++) {
if ($items[$i])){ //not necessarily the best way to check if it has a value
//do what you want with $items[$i], $color[$i], $quantity[$i], and $price[$]
}
}
For your HTML form inputs use:
<input type="text" name="item[]" />
Here is the requested HTML. I'm just learning so I'm sure there is a more efficient way to name inputs. I'm trying to group item-color-quantity-price, so that when the form is emailed, the relevant data is in a paragraph or table for each item.
<td align="center"><p><span>Item Name</span><br><input id="item1" type="text" name="item1"></p></td>
<td align="center"><p><span>Color</span><br><input id="color1" type="text" name="color1"></td>
<td align="center"><p><span>Quantity</span><br><input id="quantity1" type="text" name="quantity1"></td>
<td align="center"><p><span>Wholesale Price</span><br><input id="price1" type="text" name="price1"></td>
</tr>
<tr>
<td align="center"><p><input id="item2" type="text" name="item2"></p></td>
<td align="center"><p><input id="color2" type="text" name="color2"></p></td>
<td align="center"><p><input id="quantity2" type="text" name="quantity2"></p></td>
<td align="center"><p><input id="price2" type="text" name="price2"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item3" type="text" name="item3"></p></td>
<td align="center"><p><input id="color3" type="text" name="color3"></p></td>
<td align="center"><p><input id="quantity3" type="text" name="quantity3"></p></td>
<td align="center"><p><input id="price3" type="text" name="price3"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item4" type="text" name="item4"></p></td>
<td align="center"><p><input id="color4" type="text" name="color4"></p></td>
<td align="center"><p><input id="quantity4" type="text" name="quantity4"></p></td>
<td align="center"><p><input id="price4" type="text" name="price4"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item5" type="text" name="item5"></p></td>
<td align="center"><p><input id="color5" type="text" name="color5"></p></td>
<td align="center"><p><input id="quantity5" type="text" name="quantity5"></p></td>
<td align="center"><p><input id="price5" type="text" name="price5"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item6" type="text" name="item6"></p></td>
<td align="center"><p><input id="color6" type="text" name="color6"></p></td>
<td align="center"><p><input id="quantity6" type="text" name="quantity6"></p></td>
<td align="center"><p><input id="price6" type="text" name="price6"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item7" type="text" name="item7"></p></td>
<td align="center"><input id="color7" type="text" name="color7"></p></td>
<td align="center"><input id="quantity7" type="text" name="quantity7"></p></td>
<td align="center"><p><input id="price7" type="text" name="price7"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item8" type="text" name="item8"></p></td>
<td align="center"><p><input id="color8" type="text" name="color8"></p></td>
<td align="center"><p><input id="quantity8" type="text" name="quantity8"></p></td>
<td align="center"><p><input id="price8"type="text" name="price8"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item9" type="text" name="item9"></p></td>
<td align="center"><p><input id="color9" type="text" name="color9"></p></td>
<td align="center"><p><input id="quantity9" type="text" name="quantity9"></p></td>
<td align="center"><p><input id="price9" type="text" name="price9"></p></td>
</tr>
I converted all my input names to arrays and I have working loop. However, I need to format the foreach to produce an HTML email with table. It was working perfectly when echo-ing the data but once I formatted it to send as $message, it only sends the last $item.
Here is the foreach loop that works perfectly:
foreach ( $_POST['item'] as $items) {
{
echo '<table>';
echo '<tr>';
echo ' <td>', $items['name'], '</td>';
echo ' <td>', $items['color'], '</td>';
echo ' <td>', $items['size'], '</td>';
echo ' <td>', $items['quantity'], '</td>';
echo ' <td>', $items['price'], '</td>';
echo '</tr>';
}
echo '</table>';
}
HTMl email using the PHP mail function:
foreach ( $_POST['item'] as $items) {
$message = "
<html>
<body>
<table>
<tr>
<th>Name</th>
<th>Color</th>
<th>Size</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>" . $items['name'] . "</td>
<td>" . $items['color'] . "</td>
<td>" . $items['size'] . "</td>
<td>" . $items['quantity'] . "</td>
<td>" . $items['price'] . "</td>
</tr>
</table>
</body>
</html>
";
}
Related
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
echo "<tr>.<th>" . $row["crew_name"] . "<br></br>" . "</th>";
echo "<th>" . $row["crew_rank"] . "</th>";
echo "<th>" . $row["start_date"] . "</th>";
echo "<th>" . $row["end_date"] . "</th>";
echo "<th>" . $row["watchkeeping"] . "</th>";
echo "<th>" . $row["active"] . "</th>";
echo "<td>Edit";
echo "<td>Delete";
}
?>
editcrew.php
<table>
<form action="handlecrewedit.php" method="post">
<tr>
<td>Crew Name:</td>
<td><input type="text" name="CrewName" id ="CrewName"required></td>
</tr>
<tr>
<td>Crew Rank:</td>
<td><input type="text" name="CrewRank" id="CrewRank" required></td>
</tr>
<tr>
<td>Start Date:</td>
<td><input type="text" name="StartDate" id="StartDate" required></td>
</tr>
<tr>
<td>End Date:</td>
<td><input type="text" name="EndDate" id="EndDate" required></td>
</tr>
<tr>
<td>Payroll No:</td>
<td><input type="text" name="PayrollNo" id="PayrollNo" required></td>
</tr>
<tr>
<td>Employee No:</td>
<td><input type="text" name="EmployeeNo" id="EmployeeNo" required></td>
</tr>
<tr>
<td>Watching Keeping:</td>
<td><input type="text" name="WatchKeeping" id="WatchKeeping" required></td>
</tr>
<tr>
<td>Active:</td>
<td><input type="text" name="Active" id="Active" required></td>
</tr>
<tr>
<td><input type="submit" value="Submit" ></td>
</tr>
</form>
</table>
handlecrewedit.php
<?php
require 'dbfunction.php';
$con = getDbConnect();
$crew_id = $_POST["crew_id"];
$CrewName = $_POST["CrewName"];
$CrewRank = $_POST["CrewRank"];
$StartDate = $_POST["StartDate"];
$EndDate = $_POST["EndDate"];
$PayrollNo = $_POST["PayrollNo"];
$EmployeeNo = $_POST["EmployeeNo"];
$WatchKeeping = $_POST["WatchKeeping"];
$Active = $_POST["Active"];
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT crew_id " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $row['crew_id'] . "";
}
mysqli_query($con, $sqlQueryStr);
header('Location: crewlisting.php');
mysqli_close($con);
}
mysqli_close($con);
?>
This is another issue on my modifying entries. I'm not quite sure if I can simply copy and paste my delete code for my edit code, but here is some rough gauge of my table. Unlike the delete function, by selecting the edit function, it directs the user to the form page and it requires them to fill in the updated data.
Errors
Missing closing tag (?>) on here <form action="<?php echo $_SERVER['PHP_SELF']; ?" method="post">
$queryStr = "SELECT * " ."FROM crewlist"; should be $queryStr = "SELECT * FROM crewlist"
No closing tag comes for <br> on here echo "<tr>.<th>" . $row["crew_name"] . "<br></br>" . "</th>";
You don't know how many data passing for this $result = mysqli_query($con, $queryStr);, because there is no row count validation
There is no use of check this inside while loop. if (!mysqli_connect_errno($con))
If you are just updating the fields then you've placed the update query in the wrong place
Replace editcrew.php and handlecrewedit.php file code with below code.
editcrew.php
<table>
<form action="handlecrewedit.php" method="post">
<input type="hidden" name="crew_id" value="<?php echo $_GET['id']; ?>" />
<tr>
<td>Crew Name:</td>
<td><input type="text" name="CrewName" id ="CrewName"required></td>
</tr>
<tr>
<td>Crew Rank:</td>
<td><input type="text" name="CrewRank" id="CrewRank" required></td>
</tr>
<tr>
<td>Start Date:</td>
<td><input type="text" name="StartDate" id="StartDate" required></td>
</tr>
<tr>
<td>End Date:</td>
<td><input type="text" name="EndDate" id="EndDate" required></td>
</tr>
<tr>
<td>Payroll No:</td>
<td><input type="text" name="PayrollNo" id="PayrollNo" required></td>
</tr>
<tr>
<td>Employee No:</td>
<td><input type="text" name="EmployeeNo" id="EmployeeNo" required></td>
</tr>
<tr>
<td>Watching Keeping:</td>
<td><input type="text" name="WatchKeeping" id="WatchKeeping" required></td>
</tr>
<tr>
<td>Active:</td>
<td><input type="text" name="Active" id="Active" required></td>
</tr>
<tr>
<td><input type="submit" value="Submit" ></td>
</tr>
</form>
</table>
handlecrewedit.php
<?php
require 'dbfunction.php';
$con = getDbConnect();
$crew_id = $_POST["crew_id"];
$CrewName = $_POST["CrewName"];
$CrewRank = $_POST["CrewRank"];
$StartDate = $_POST["StartDate"];
$EndDate = $_POST["EndDate"];
$PayrollNo = $_POST["PayrollNo"];
$EmployeeNo = $_POST["EmployeeNo"];
$WatchKeeping = $_POST["WatchKeeping"];
$Active = $_POST["Active"];
if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $crew_id . "";
mysqli_query($con, $sqlQueryStr);
}
header('Location: crewlisting.php');
mysqli_close($con);
?>
I think the suggested answers miss a small point.
It only updates the first row because you exit the while loop with the redirection header.
header('Location: crewlisting.php');
mysqli_close($con);
Place those two lines outside your while loop, and it should update each row.
Your while loop will than be:
while ($row = mysqli_fetch_array($result)) {
// not needed. if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $row['crew_id'] . "";
//} closing bracket of if, but the if is not needed.
mysqli_query($con, $sqlQueryStr);
}
//after updating all rows, redirect
header('Location: crewlisting.php');
mysqli_close($con);
I have built an HTML form that has buttons to add rows for multiple inputs. I want to email all the rows with the input data no matter how many rows are added. So far I get the email but its only 1 row of data and all the input fields are saying "Array" and I receive the notice of "Array to string conversion on line 34" & "Array to string conversion on line 41"
Is this even possible?
HTML Form Code:
<form action="Email.php" method="POST">
<table id="2HL" name="Pass">
<tbody>
<tr>
<td><font style="color: #b22222; font-size:120%">Date</font></td>
<td><input type="datetime" name="Date"></td>
</tr>
<tr>
<td><font style="color: #b22222; font-size:120%">Team Lead</font></td>
<td><input type="text" name="Team_Lead"></td>
</tr>
<tr>
<td><font style="color: #00008b; font-size:120%">End of Shift Information:</font></td>
</tr>
<tr>
<table id="Cellinfo">
<tbody>
<tr>
<td Type="text" name="Cell"><font style="color: #b22222; font-size:100%">CELL</font></td>
<td Type="text" name="Goal"><font style="color: #b22222; font-size:100%">GOAL</font></td>
<td Type="text" name="Comp"><font style="color: #b22222; font-size:100%">COMP</font></td>
<td Type="text" name="LTD"><font style="color: #b22222; font-size:100%">LTD</font></td>
<td Type="text" name="WET_SKU"><font style="color: #b22222; font-size:100%">WET SKU</font></td>
</tr>
<tr id="clone">
<td><input type="text" name="Cell[]"></td>
<td><input type="text" name="Goal[]"></td>
<td><input type="text" name="Comp[]"></td>
<td><input type="text" name="LTD[]"></td>
<td><input type="text" name="WET_SKU[]"></td>
</tr>
</tbody>
</table>
<input type="button" onclick="cloneRow()" value="ADD ROW" /><br>
</tr>
<tr>
<td><font style="color: #00008b; font-size:120%">Impediment Notes:</font></td>
</tr>
<tr>
<table id="impediment">
<tbody>
<tr>
<td Type="text" name="Cell0"><font style="color: #b22222; font-size:100%">CELL</font></td>
<td Type="text" name="SKU0"><font style="color: #b22222; font-size:100%">SKU</font></td>
<td Type="text" name="Part0"><font style="color: #b22222; font-size:100%">PART #</font></td>
<td Type="text" name="Impediment0"><font style="color: #b22222; font-size:100%">IMPEDIMENT TYPE</font></td>
<td Type="text" name="QTYadj0"><font style="color: #b22222; font-size:100%">QTY ADJUSTED</font></td>
<td Type="text" name="Partloc0"><font style="color: #b22222; font-size:100%">PART LOCATION</font></td>
<td Type="text" name="Comments0"><font style="color: #b22222; font-size:100%">TEAM LEAD COMMENTS</font></td>
</tr>
<tr id="clone1">
<td><input type="text" name="Cella[]"></td>
<td><input type="text" name="SKU[]"></td>
<td><input type="text" name="Part[]"></td>
<td><input type="text" name="Impediment[]"></td>
<td><input type="text" name="QTYadj[]"></td>
<td><input type="text" name="Partloc[]"></td>
<td><input type="text" name="Comments[]" size="75"></td>
</tr>
</tbody>
</table>
<input type="button" onclick="cloneimpediment()" value="ADD ROW" /><br>
</tr>
</tbody>
</table>
<p>
<input type="submit" value="Email Form">
</P>
</form>
Java Code to Add Rows:
<script type="text/javascript">
function cloneRow()
{
var row = document.getElementById("clone"); // find row to copy
var table = document.getElementById("Cellinfo"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "clone"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function cloneimpediment()
{
var row = document.getElementById("clone1"); // find row to copy
var table = document.getElementById("impediment"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "clone1"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
</script>
PHP Code Here:
<?php foreach($_POST as $key => $value){
$Date = $_POST['Date'];
$Team_Lead = $_POST['Team_Lead'];
$Cell = $_POST['Cell'];
$Goal = $_POST['Goal'];
$Comp = $_POST['Comp'];
$LTD = $_POST['LTD'];
$WET_SKU = $_POST['WET_SKU'];
$Cella = $_POST['Cella'];
$SKU = $_POST['SKU'];
$Part = $_POST['Part'];
$Impediment = $_POST['Impediment'];
$QTYadj = $_POST['QTYadj'];
$Partloc = $_POST['Partloc'];
$Comments = $_POST['Comments'];
}
$email_from = 'TestTeamLead#moen.com';
$email_subject = "Pass Down Test";
$email_body = "<html><body>";
$email_body .= '<table border="1">';
$email_body .= "<tr><td>Date</td><td>$Date</td></tr>";
$email_body .= "<tr><td>Team Lead</td><td>$Team_Lead</td></tr>";
$email_body .= "</table>";
$email_body .= "<br>";
$email_body .= "END OF SHIFT INFORMATION:";
$email_body .= "<br>";
$email_body .= '<table border="1">';
$email_body .= '<tr><td>Cell</td><td>Goal</td><td>Comp</td><td>LTD</td><td>WET SKU</td></tr>';
$email_body .= "<tr><td>$Cell</td><td>$Goal</td><td>$Comp</td><td>$LTD</td><td>$WET_SKU</td></tr>";
$email_body .= "</table>";
$email_body .= "<br>";
$email_body .= "IMPEDIMENT NOTES:";
$email_body .= "<br>";
$email_body .= '<table border="1">';
$email_body .= '<tr><td>Cell</td><td>SKU</td><td>PART #</td><td>ImpedimentType</td><td>QTY Adjusted</td><td>Part Location</td><td>TEAM LEAD Comments</td></tr>';
$email_body .= "<tr><td>$Cella</td><td>$SKU</td><td>$Part</td><td>$Impediment</td><td>$QTYadj</td><td>$Partloc</td><td>$Comments</td></tr>";
$email_body .= "</table>";
?>
Well, I guess here foreach($_POST as $key => $value) you want to iterate through all of the HTML table rows. But the thing is that you have on server exactly what you've specified on client.
Try print_r($_POST), so you'll have an idea of the data that comes to server. You should iterate through a random key of yours or rewrite the client code to get the php script in accordance.
Code on line 31 and 41 are arrays, you should iterate in for loop to show them in html, that is why you get array notice.why are your input field name atribute set as array []?
I dont get what im doing wrong here..
i have about 125 product in the table but i get only the last product from the table so it shows only one item... this is a simple calculator to provide the sales person and the customer how much box they would need and how much it would cost a quick estimate.
Thank you for the help in advance..
<?php
include('admincik/config.php');
include ('birlikte/ac.thumbs.php');
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM Calculator ORDER BY isim") or die(mysql_error());
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
$resim = $info['resim'];
$isim = $info[isim];
$boyut = $info[boyut];
$pcs = $info[adet];
$sqft = $info[sqft];
$price = $info[price];
}
/////////Formdan gelen yada Giden//////////////
$length =htmlspecialchars(stripslashes($_POST['Length']));
$width =htmlspecialchars(stripslashes($_POST['Width']));
$TileNameList = "<option value=\"$sqft\">$isim $boyut</option>";
/////Matematiksel islemler/////////
$equals = $length * $width;
$box = round($equals / $sqft);
$sqftbox = $box * $sqft;
$TotalPrice = $sqftbox * $price
?>
<div class="ana">
<table width="900" height="199" border="1">
<tr>
<td width="150">Name</td>
<td width="150">Length</td>
<td width="150">Width</td>
<td width="150">Total Sqft Area</td>
<td width="200">Box Needed /Total Sqft</td>
<td width="100">Price</td>
</tr>
<tr>
<td><form id="form5" name="form5" method="post" action="">
<select name="TileName" id="TileName">
<?php echo ($TileNameList); ?>
</select>
</td>
<td><input name="Length" type="text" id="Length"/></td>
<td><input type="text" name="Width" id="Width"/></td>
<td><input type="text" name="Sqft" id="Sqft" value="<?php echo ($equals); ?>"/></td>
<td><?php echo "You will need <span style=\"color:red\">$box</span> Boxes<br> Which is <span style=\"color:red\">$sqftbox</span> "; ?></td>
<td><?php echo "$$TotalPrice"; ?></td>
</tr>
<tr >
<td colspan="6" align="center">
<input type="submit" name="Submit" id="Submit" value="Submit" />
</form></td>
</tr>
</table>
</div>
Your loop doesn't append to $TileNameList because it exists outside of it. It actually replaces it's value. Try:
<?php
include('admincik/config.php');
include ('birlikte/ac.thumbs.php');
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM Calculator ORDER BY isim") or die(mysql_error());
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
$resim = $info['resim'];
$isim = $info[isim];
$boyut = $info[boyut];
$pcs = $info[adet];
$sqft = $info[sqft];
$price = $info[price];
$TileNameList .= "<option value=\"$sqft\">$isim $boyut</option>"; // NOTE THE .=
}
/////////Formdan gelen yada Giden//////////////
$length =htmlspecialchars(stripslashes($_POST['Length']));
$width =htmlspecialchars(stripslashes($_POST['Width']));
/////Matematiksel islemler/////////
$equals = $length * $width;
$box = round($equals / $sqft);
$sqftbox = $box * $sqft;
$TotalPrice = $sqftbox * $price
?>
<div class="ana">
<table width="900" height="199" border="1">
<tr>
<td width="150">Name</td>
<td width="150">Length</td>
<td width="150">Width</td>
<td width="150">Total Sqft Area</td>
<td width="200">Box Needed /Total Sqft</td>
<td width="100">Price</td>
</tr>
<tr>
<td><form id="form5" name="form5" method="post" action="">
<select name="TileName" id="TileName">
<?php echo ($TileNameList); ?>
</select>
</td>
<td><input name="Length" type="text" id="Length"/></td>
<td><input type="text" name="Width" id="Width"/></td>
<td><input type="text" name="Sqft" id="Sqft" value="<?php echo ($equals); ?>"/></td>
<td><?php echo "You will need <span style=\"color:red\">$box</span> Boxes<br> Which is <span style=\"color:red\">$sqftbox</span> "; ?></td>
<td><?php echo "$$TotalPrice"; ?></td>
</tr>
<tr >
<td colspan="6" align="center">
<input type="submit" name="Submit" id="Submit" value="Submit" />
</form></td>
</tr>
</table>
</div>
I wonder is it possible to keep the user input inside form field after form submitted, so that the user can update the entry. I've a html registration form [with some JS validation], then a php file to insert data to sql & meanwhile display back the inserted data in a table view. i also include the form's html code in php file so i can see the form after being submitted. but i couldn't keep the data in the field after form submitted! here is the form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="insert.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Submit" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
</body>
</html>
here is the insert.php file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="update.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Update" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
<br>
</div>
</form>
<div align="center">
<?php
if (!mysql_connect('localhost', 'root', '')) {
echo "Connected";
}
mysql_select_db("workshop");
// Get values from form
$ic = mysql_real_escape_string($_POST['ic']);
$name = mysql_real_escape_string($_POST['name']);
$contact = mysql_real_escape_string($_POST['contact']);
$mail = mysql_real_escape_string($_POST['mail']);
$address = mysql_real_escape_string($_POST['address']);
if (staff_detail_exist($ic) == "available") {
insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype);
echo "<p style='text-align:center; color:green;'>" . "Workshop application successful! You will be notified shortly via E-mail after confirmation! Thank You!";
} else if (staff_detail_exist($ic) == "exist") {
echo "<p style='text-align:center; color:red;'>" . "Record already exists! Please enter another Staff ID. Thank You!" . "</p>";
}
function insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype) {
$sql = "INSERT INTO apply (staffid, staffname, staffno, staffemail, staffaddress, paytype) VALUES ('$ic', '$name', '$contact', '$mail', '$address','$paytype')";
mysql_query($sql);
}
function staff_detail_exist($ic) {
$result = null;
$sql = "SELECT * FROM apply WHERE staffid = '$ic'";
$data = mysql_query($sql);
if (mysql_num_rows($data) == 0) {
$result = "available";
} else {
$result = "exist";
}
return $result;
}
$staffid = $_POST['ic'];
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("workshop", $con);
$result = mysql_query("SELECT * FROM apply where staffid = '$ic'");
echo "<table width=400 border=1 cellpadding=0 align=center>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<th>Staff/IC Number: </th><td>" . "<center>" . $row['staffid'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Name: </th><td>" . "<center>" . $row['staffname'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Email: </th><td>" . "<center>" . $row['staffemail'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Contact No.: </th><td>" . "<center>" . $row['staffno'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Address: </th><td>" . "<center>" . $row['staffaddress'] . "</center>" . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
I've tried to add like value="<? echo "$row['staffid']"?>" in the form's field at php file but no luck! I've only basic in php. So, any help? thank you!
thanks all, its finally working :) i've used value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" inside the input tag. so, its like: <input type="text" name="myField" value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" /> where myField is input name & myField_db is the column name from database.
Take the form posted values just above your html code like this
<?php
if (isset($_POST["submit"]) && $_POST["submit"]=='Submit') {
$name=$_POST["name"];
}
?>
And echo it in your html form.
<input name="name" type="text" id="name" size="45" value="<? echo $name?>"/>
I've used this function a few times; quite handy
function getPost($field){
return (isset($_POST[$field]) && $_POST[$field] != "" ? $_POST[$field] : "");
}
Usage
<input type="text" name="contact" value="<?php echo getPost("contact"); ?>" />
This is for the cases where a user submits information and is for some reason sent back to the form again - perhaps their entries didn't pass PHP validation, for example.
Please help me regarding the problem specified in the title.
Input form page code:
<?
db_connect();
$query1 = "SELECT *, DATE_FORMAT(eventdate,'%m/%d/%y') AS
eventdate,DATE_FORMAT(throughdate,'%m/%d/%y') AS throughdate FROM events WHERE id = " . mysql_real_escape_string($_REQUEST['id']);
$result1 = mysql_query($query1) or die("Error - query failed " . mysql_error());
if ( mysql_num_rows($result1) == 0 ) {
print "<p>Error - no such event.</p>\n";
return;
}
else {
$qry_event1 = mysql_fetch_array($result1);
}
// default the formaction to the query
if (! isset($_REQUEST['formaction']) ) { $_REQUEST['formaction'] = 'query'; }
?>
<form name="eventform" method="post" action="act_updevent.php">
<input type="hidden" name="submit_check" value="1">
<input type="hidden" name="formaction" value="form">
<!-- if we are editing, $id will exist. Pass it along. -->
<input type="hidden" name="id" value="<?php $qry_event1['id'];?>">
<table>
<tr>
<td align="right" valign="center"><b><? displayformlabel('eventdate','Event Date:')?>
</b></td>
<td><input name="eventdate" value="<? echo $qry_event1['eventdate']; ?>">
<a name="calendar1here" id="calendar1here" href="JavaScript:;"
onClick="cal1.select(document.forms[0].eventdate,'calendar1here','MM/dd/yy'); return
false;">
<img src="resources/calendar.gif" alt="Calendar Icon" width="20" height="20"
border="0"></a>
</td>
</tr>
<tr>
<td align="right" valign="center"><b><? displayformlabel('throughdate','Through:')?>
</b></td>
<td><input name="throughdate" value="<? echo $qry_event1['throughdate']; ?>">
<a name="calendar2here" id="calendar2here" href="JavaScript:;"
onClick="cal2.select(document.forms[0].throughdate,'calendar2here','MM/dd/yy'); return
false;">
<img src="resources/calendar.gif" alt="Calendar Icon" width="20" height="20"
border="0"></a>
<span class="formnotes">Leave blank if only one day event</span>
</td>
</tr>
<tr>
<td align="right"><b><? displayformlabel('title','Event Title:')?></b></td>
<td><input name="title" size="50" maxlength="50" value="<? echo $qry_event1['title'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('website','Event Website:')?></td>
<td><input name="website" size="50" maxlength="100" value="<? echo
$qry_event1['website']; ?>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('email','Event Email:')?></td>
<td><input name="email" size="50" maxlength="100" value="<? echo
$qry_event1['email'];?>"></td>
</tr>
<tr>
<td align="right" valign="top"><? displayformlabel('notes','Notes:')?></td>
<td><textarea name="notes" style="width: 320px; height: 60px;"><? echo
$qry_event1['notes']; ?></textarea></td>
</tr>
<tr>
<td align="right"><? displayformlabel('venue','Venue:')?></td>
<td><input name="venue" size="50" maxlength="50" value="<? echo $qry_event1['venue'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('address','Address:')?></td>
<td><input name="address" size="50" maxlength="50" value="<?echo
$qry_event1['address'];?>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('city','City:')?></td>
<td><input name="city" size="50" maxlength="50" value="<?echo $qry_event1['city'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('state','State:')?></td>
<td><input name="state" size="3" maxlength="2" value="<?echo $qry_event1['state'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('lat','Latitude:')?></td>
<td><input name="lat" size="15" maxlength="15" value="<? echo $qry_event1['lat'];?>">
</td>
</tr>
<tr>
<td align="right"><? displayformlabel('lon','Longitude:')?></td>
<td><input name="lon" size="15" maxlength="15" value="<? echo $qry_event1['lon'];?>">
<span class="formnotes">Look up
coordinates using above address information.</span>
</td>
</tr>
<tr>
<td align="right"><? displayformlabel('accurate','Accurate:')?></td>
<td><input name="accurate" type="checkbox" value="1" <?php if
(isset($qry_event1['accurate'])) { echo 'checked="checked"'; }?>>
<a href="JavaScript:;" class="formnotes" onClick="window.open('<?php
print $vsf->self;?>?action=accuratehelp','helpwin','width=435,height=220');">Whats
this?</a>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
Update page:
<?php
// updates a record in the database
// do validation (shared with update logic)
$id = $_REQUEST['id'];
$eventdate = $_REQUEST['eventdate'];
$throughdate = $_REQUEST['throughdate'];
$title = $_REQUEST['title'];
$website = $_REQUEST['website'];
$email = $_REQUEST['email'];
$notes = $_REQUEST['notes'];
$venue = $_REQUEST['venue'];
$address = $_REQUEST['address'];
$city = $_REQUEST['city'];
$state = $_REQUEST['state'];
$lat = $_REQUEST['lat'];
$lon = $_REQUEST['lon'];
$accurate = $_REQUEST['accurate'];
$errorwasthrown="";
$database = 'mapcal';
// database server
$dbsvr = 'localhost';
// username
$dbuser = 'root';
// password
$dbpass = 'usbw';
function db_connect() {
global $dbsvr,$dbuser,$dbpass,$database;
static $dbcon;
if ( ! $dbcon ) {
$dbcon = mysql_connect($dbsvr,$dbuser,$dbpass);
if (! mysql_select_db($database) ) {
die("Failure connecting to database - " . mysql_error());
}
}
}
if (! $eventdate ) {
adderrmsg('eventdate','Event date cannot be blank.');
$errorwasthrown=1;
}
else {
// else date wasn't blank, so validate it
if (! preg_match("/^\d\d\/\d\d\/\d\d$/",$eventdate) ) {
adderrmsg('eventdate',"Event date must be in format mm/dd/yy.");
$errorwasthrown=1;
}
}
if ($throughdate && ! preg_match("/^\d\d\/\d\d\/\d\d$/",$throughdate) ) {
adderrmsg('throughdate',"Through date must be in format mm/dd/yy.");
$errorwasthrown=1;
}
if (! $title ) {
adderrmsg('title','Title cannot be blank.');
$errorwasthrown=1;
}
if ($errorwasthrown) {
include('dsp_editevent.php');
}
else {
db_connect();
// format the date correctly for mysql
$dateparts = split("/",$eventdate);
$eventdate = "$dateparts[2]/$dateparts[0]/$dateparts[1]";
if ($throughdate) {
$dateparts = split("/",$throughdate);
$throughdate = "$dateparts[2]/$dateparts[0]/$dateparts[1]";
$throughdate = "'" . mysql_real_escape_string($throughdate) . "'";
}
else {
$throughdate = 'NULL';
}
// format event website if necessary
if ($website && ! preg_match("/:\/\//",$website) ) {
$website = "http://" . $website;
}
// update record in the database
$query = "UPDATE events SET ";
$query .= "eventdate = '" . mysql_real_escape_string($eventdate) . "', " .
"throughdate = " . $throughdate . ", " .
"title = '" . mysql_real_escape_string($title) . "', " .
"website = '" . mysql_real_escape_string($website) . "', " .
"email = '" . mysql_real_escape_string($email) . "', " .
"notes = '" . mysql_real_escape_string($notes) . "', " .
"venue = '" . mysql_real_escape_string($venue) . "', " .
"address = '" . mysql_real_escape_string($address) . "', " .
"city = '" . mysql_real_escape_string($city) . "', " .
"state = '" . mysql_real_escape_string($state) . "', " .
"lat = '" . mysql_real_escape_string($lat) . "', " .
"lon = '" . mysql_real_escape_string($lon) . "', " .
"accurate = '" . mysql_real_escape_string($accurate) . "' " .
"WHERE id = " . mysql_real_escape_string($id);
if ( ! mysql_query($query) ) {
exit("Query failed! - $query");
}
print "<p style='color: green'>Event <b>$title</b> was updated.</p>\n";
include('dsp_listevents.php');
} // close else ! errorwasthrown
?>
What i can see after printing the query is that it is not getting the value of id but all the fields from the form but why?
Keep the Id value in quotes.
"WHERE id = '" . mysql_real_escape_string($id)."'";