i am creating a form to do billing and i had a fatal error on the total_amt_array. Also, how do i parse an array of items into database? The form is in the Create Invoice and the invoicesubmit is where it adds all the arrays into the database. Anyone can explain to me why i can't make a total sum of the discount, amount and quantity array.
Also, does anyone have an easier way to calculate all of the total_amt_array. I've searched stackoverflow and others find the final total amount by adding the entire cost column to get the final total cost amount.
Create Invoice
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var count = 0;
function addTextArea(){
count= count+1;
var div = document.getElementById('name');
div.innerHTML += "<div> <input type='text' name='name[]' value='' "+"id=name"+count+"> </div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('quantity');
div.innerHTML += "<div><input type='text' name='quantity[]' value ='' "+"id=quantity"+count+"></div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('amount');
div.innerHTML += "<div><input type='text' name='amount[]' value ='' "+"id=amount"+count+"></div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('discount');
div.innerHTML += "<div><input type='text' name='discount[]' value ='' "+"id=discount"+count+"></div>";
div.innerHTML += "\n<br />";
}
function removeTextArea(){
document.getElementById("name"+count).remove();
document.getElementById("quantity"+count).remove();
document.getElementById("amount"+count).remove();
document.getElementById("discount"+count).remove();
count = count-1;
}
</script>
</head>
<body>
<form action="invoicesubmit.php" method="POST">
<?php
echo "<table border='2'>\n";
echo "<tr>\n";
echo "<th>Description</th>\n";
echo "<th>Quantity</th>\n";
echo "<th>Amount($)</th>\n";
echo "<th>Discount(%)</th>\n";
echo "</tr>";
echo "<tr>";
echo "<td>"?><input type='text' size="50" name='name[]' value='Examination and Consultation' readonly/><?php "</td>";
echo "<td>"?><input type='text' size="50" name='quantity[]' value='' /><?php "</td>";
echo "<td>"?><input type='text' size="50" name='amount[]' value='' /><?php "</td>";
echo "<td>"?><input type='text' size="50" name='discount[]' value='' /><?php "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>"?><div id="name"></div> <?php "</td>";
echo "<td>"?><div id="quantity"></div> <?php "</td>";
echo "<td>"?><div id="amount"></div> <?php "</td>";
echo "<td>"?><div id="discount"></div> <?php "</td>";
echo "</tr>";
?>
<br />
<input type="button" value="Add Description" onClick="addTextArea();">
<input type="button" value="Remove Description" onClick="removeTextArea();">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
invoicesubmit
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php
if (isset($_POST['submit'])) {
// Process the form
$name_array = $_POST['name'];
$quantity_array = $_POST['quantity'];
$amount_array = $_POST['amount'];
$discount_array = $_POST['discount'];
$total_amt_array = ($amount_array - ($amount_array * ($discount_array/ 100))) * $quantity_array ;
for ($i =0; $i < count($name_array); $i++) {
$name = $name_array[$i];
$quantity = $quantity_array[$i];
$amount = $amount_array[$i];
$discount = $discount_array[$i];
$total_amt = $total_amt_array[$i];
echo $name;
echo "<br />";
echo $quantity;
echo "<br />";
echo $amount;
echo "<br />";
echo $discount;
echo "<br />";
echo $total_amt;
}
}
/*
//validations
$required_fields = array("name", "quantity", "amount", "discount");
validate_presences($required_fields);
$fields_with_max_lengths = array("name" => 200);
validate_max_lengths($fields_with_max_lengths);
if (!empty($errors)) {
$_SESSION["errors"] = $errors;
redirect_to("create_invoice.php");
}*/
/*
// 2. Perform database query
$query = "INSERT INTO invoicesub (";
$query .= " description, quantity, amount, discount, total";
$query .= ") VALUES (";
$query .= " '{$name}', '{$quantity}', '{$amount}', '{$discount}', '{$total}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["message"] = "Subject created.";
redirect_to("confirm_invoice.php");
}
else {
// Failure
$_SESSION["message"] = "Subject creation failed.";
redirect_to("create_invoice.php");
}
} else {
// This is probably a GET request
redirect_to("create_invoice.php");
} */
?>
<?php
if (isset($connection)) { mysqli_close($connection); }
?>
First you have:
echo "<td>"?><input type='text' size="50" name='amount[]' value='' /><?php "</td>";
^^---create an array in $_POST
Then:
$amount_array = $_POST['amount'];
^^^^^^^^^^^----this is now an array
Then:
$total_amt_array = ($amount_array - ($amount_array * ($discount_array/ 100))) * $quantity_array ;
This code boils down to:
$total_amt_array = Array - (Array * (Array / 100))) * Array;
You cannot multiply/divide arrays in PHP.
Related
I currently have these PHP pages which lets me add a record to a database. (in this case its members) It works perfectly in the sense that I can ADD, DELETE and VIEW. But Im not sure how to get the edit(or UPDATE functionality working.
Here is my db connection Code:
<?php
// Server Info
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'gamgam';
// Connect to database
$connection = new mysqli($server, $username, $password, $database);
?>
Here is my Add Code:
<!DOCTYPE html>
<html>
<head><title>Insert Users</title></head>
<body>
<h2>Insert User Confirmation</h2>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post"/> <br>
<?php
require_once('connection.php');
echo "<label for='memberID' >Member ID:</label>";
echo "<input type='text' name='memberID' id='memberID' />";
echo "<br /><br />";
echo "<label for='username' >Username:</label>";
echo "<input type='text' name='username' id='username' />";
echo "<br /><br />";
echo "<label for='password' >Password:</label>";
echo "<input type='password' name='password' id='password' />";
echo "<br /><br />";
echo "<label for='fName' >Firstname:</label>";
echo "<input type='text' name='fName' id='fName' />";
echo "<br /><br />";
echo "<label for='lName' >Lastname:</label>";
echo "<input type='text' name='lName' id='lName' />";
echo "<br /><br />";
echo "<label for='address' >Address:</label>";
echo "<input type='text' name='address' id='address' />";
echo "<br /><br />";
echo "<label for='email' >Email:</label>";
echo "<input type='text' name='email' id='email' />";
echo "<br /><br />";
echo "<input type='submit' name='submit' value='Submit' />";
echo "<input type='reset' value='Clear' />";
echo "<br /><br />";
?>
</form>
</section>
<p><a href='login.php'>Login</a></p>
<?php
if(!isset($_POST['submit'])) {
echo 'Please Register';
} else {
$memberID = $_POST['memberID'];
$username = $_POST['username'];
$password = $_POST['password'];
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$address = $_POST['address'];
$email = $_POST['email'];
$query = "INSERT INTO `members`
(MemberID, Username, Password, FirstName, LastName,
StreetAddress, Email)
VALUES ('$memberID', '$username', '$password', '$fName',
'$lName', '$address', '$email')";
mysqli_query($connection, $query)
or die(mysqli_error($connection));
$rc = mysqli_affected_rows($connection);
if ($rc==1)
{
echo '<h4>The database has been updated with the following details: </h4> ';
echo 'MemberID: '.$memberID.'<br />';
echo 'Username: '.$username.'<br />';
echo 'Password: '.$password.'<br />';
echo 'First Name: '.$fName.'<br />';
echo 'Last Name: '.$lName.'<br />';
echo 'Address: '.$address.'<br />';
echo 'Email: '.$email.'<br />';
} else {
echo '<p>The data was not entered into the database this time.</p>';
}
}
?>
</body>
</html>
Here is my View Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<table border="1" style="width:100%" >
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include('connection.php');
// get results from database
$result = mysqli_query($connection, "SELECT * FROM members")
or die(mysqli_error());
// loop through results of database query, displaying them in the table
while($row = mysqli_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['MemberID'] . '</td>';
echo '<td>' . $row['Username'] . '</td>';
echo '<td>' . $row['Password'] . '</td>';
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['StreetAddress'] . '</td>';
echo '<td>' . $row['Email'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
And here is the Delete Code:
<?php
// Connect to the database
include('connection.php');
// Confirm that the 'code' variable has been set
if (isset($_GET['MemberID']))
{
// Get the 'MemberID' variable from the URL
$MemberID = $_GET['MemberID'];
// Delete record from database
if ($stmt = $connection->prepare("DELETE FROM members WHERE MemberID = ? LIMIT 1")) {
$stmt->bind_param("i",$MemberID);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: could not prepare SQL statement.";
}
$connection->close();
// Redirect user after delete is successful
header("Location: view.php");
} else {
// If the 'code' variable isn't set, redirect the user
header("Location: view.php");
}
?>
I have gone through many basic php form templates online trying to incorporate what they have done to achieve results but have not had any success. What code needs to be written for my website to have the functionality to edit records already created in the database without going through phpmyadmin. Any help is apreciated.
Edit will be just just like Add, but you need to read the record first and populate the field values.
Start with the code from add and do something like:
<?php $MemberID = (int) $_GET['MemberID']; ?>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post"/> <br>
<input type="hidden" name="MemberID" value="<?php echo $MemberID; ?>"
<?php
require_once('connection.php');
$result = mysqli_query($connection, "SELECT * FROM members where MemberID = $MemberID") or die(mysqli_error());
// loop through results of database query, displaying them in the table
$row = mysqli_fetch_assoc($result);
extract($row);
echo "<label for='memberID' >Member ID:</label>";
echo "$memberID"; // member ID should not be editable
echo "<br /><br />";
echo "<label for='username' >Username:</label>";
echo "<input type='text' name='username' id='username' value="$username" />";
echo "<br /><br />";
The PHP code will have a query like
`UPDATE `members` SET `username` = '$username' ... WHERE `MemberID` = '$MemberID'"
im creating an invoice function. It involves 3 pages.
The first page which is a form that takes in the variable of customer name, description, amount, quantity and discount.
The second page parses all these variable, make a new variable called total that will calculate amount X quantity minus away the discount and then insert into database then redirect to the third page.
The Third Page
Is supposed to sum the total column for a final total variable. How do i use the sum function to calculate the total in order to get the final total? And also how do i store all the variables printed out so that i can store them into database?
E.g. i want to print out all the descriptions, customer name, amount, quantity and total entered in page one and then add the final total which was calculated in page 3 .
Page one(submit 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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var count = 0;
function addTextArea() {
count = count + 1;
var div = document.getElementById('name');
div.innerHTML += "<div> <input type='text' name='name[]' value='' " + "id=name" + count + "> </div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('quantity');
div.innerHTML += "<div><input type='text' name='quantity[]' value ='' " + "id=quantity" + count + "></div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('amount');
div.innerHTML += "<div><input type='text' name='amount[]' value ='' " + "id=amount" + count + "></div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('discount');
div.innerHTML += "<div><input type='text' name='discount[]' value ='' " + "id=discount" + count + "></div>";
div.innerHTML += "\n<br />";
}
function removeTextArea() {
document.getElementById("name" + count).remove();
document.getElementById("quantity" + count).remove();
document.getElementById("amount" + count).remove();
document.getElementById("discount" + count).remove();
count = count - 1;
}
</script>
</head>
<body>
<form action="invoicesubmit.php" method="POST">
<?php
echo "<table border='2'>\n";
echo "<tr>\n";
echo "<th>Description</th>\n";
echo "<th>Quantity</th>\n";
echo "<th>Amount($)</th>\n";
echo "<th>Discount(%)</th>\n";
echo "</tr>"; echo "<tr>";
echo "<td>"?>
<input type='text' size="50" name='name[]' value='Examination and Consultation' readonly/>
<?php "</td>"; echo "<td>"?>
<input type='text' size="50" name='quantity[]' value='' />
<?php "</td>";
echo "<td>"?>
<input type='text' size="50" name='amount[]' value='' />
<?php "</td>";
echo "<td>"?>
<input type='text' size="50" name='discount[]' value='' />
<?php "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>"?>
<div id="name"></div>
<?php "</td>"; echo "<td>"?>
<div id="quantity"></div>
<?php "</td>"; echo "<td>"?>
<div id="amount"></div>
<?php "</td>"; echo "<td>"?>
<div id="discount"></div>
<?php "</td>";
echo "</tr>"; ?> <br />
<input type="button" value="Add Description" onClick="addTextArea();">
Customer Name: <input type="text" value="" name="cust_name" />
<input type="button" value="Remove Description" onClick="removeTextArea();">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
Page Two (Store into database)
<?php require_once ("includes/session.php");?>
<?php require_once ("includes/db_connection.php");?>
<?php require_once ("includes/functions.php");?>
<?php require_once ("includes/validation_function.php");?>
<?php
echo "<table border='1'>\n";
echo "<tr>\n";
echo "<th>Description</th>\n";
echo "<th>Quantity</th>\n";
echo "<th>Amount($)</th>\n";
echo "<th>Discount(%)</th>\n";
echo "<th>Total_amt</th>\n";
echo "</tr>";
<?php
if (isset($_POST['submit']))
{ // Process the form
$name_array = $_POST['name'];
$quantity_array = $_POST['quantity'];
$amount_array = $_POST['amount'];
$discount_array = $_POST['discount'];
for ($i = 0; $i < count($name_array); $i++)
{
$name = $name_array[$i];
$quantity = $quantity_array[$i];
$amount = $amount_array[$i];
$discount = $discount_array[$i];
$total_amt = ($amount - ($amount * ($discount / 100))) * $quantity;
$cust_name = mysqlprep($_POST["cust_name"]);
global $connection;
$query = "INSERT INTO invoicesub (";
$query.= " cust_name, description, quantity, amount, discount, total";
$query.= ") VALUES (";
$query.= " '{$cust_name}', '{$name}', {$quantity}, {$amount}, {$discount}, {$total}";
$query.= ")";
$result = mysqli_query($connection, $query);
echo "<tr>";
echo "<td>" . $name . "</td>";
echo "<td>" . $quantity . "</td>";
echo "<td>" . "$" . $amount . "</td>";
echo "<td>" . $discount . "%" . "</td>";
echo "<td>" . "$" . $total_amt . "</td>";
echo "</tr>";
if ($result)
{
redirect_to("invoicesubmitfinal.php");
}
}
?>
page three (Print and store into 2nd database)
<?php
$query = "SELECT * ";
$query.= "FROM invoicesub";
$result = mysqli_query("SELECT sum(amount) FROM invoicesub") or die(mysqli_error());
while ($rows = mysql_fetch_array($result))
{
$result1 = mysqli_query("SELECT sum(quantity) FROM invoicesub") or die(mysqli_error());
while ($rows1 = mysqli_fetch_array($result1))
{
$result2 = mysqli_query("SELECT sum(total) FROM invoicesub") or die(mysqli_error());
while ($rows2 = mysqli_fetch_array($result2))
{
echo $rows['amount'];
echo $rows1['quantity'];
echo $rows2['total'];
$finaltotal = $rows2['total'];
}
}
}
?>
Since, your requirement is not really understandable, i tried clearing some errors & changed the SQL. if you, refrain your questions, along with the included function & connection files, we can only take a look. The modified codes are shown below.
invoicesubmit.php
<?php require_once ("includes/session.php");?>
<?php require_once ("includes/db_connection.php");?>
<?php require_once ("includes/functions.php");?>
<?php require_once ("includes/validation_function.php");?>
<?php
echo "<table border='1'>\n";
echo "<tr>\n";
echo "<th>Description</th>\n";
echo "<th>Quantity</th>\n";
echo "<th>Amount($)</th>\n";
echo "<th>Discount(%)</th>\n";
echo "<th>Total_amt</th>\n";
echo "</tr>";
if (isset($_POST['submit'])){ // Process the form
$name_array = $_POST['name'];
$quantity_array = $_POST['quantity'];
print_r($quantity_array);
$amount_array = $_POST['amount'];
$discount_array = $_POST['discount'];
for ($i = 1; $i < count($name_array); $i++){
$name = $name_array[$i];
$quantity = $quantity_array[$i];
$amount = $amount_array[$i];
$discount = $discount_array[$i];
$total_amt = ($amount - ($amount * ($discount / 100))) * $quantity;
$cust_name = mysqlprep( $_POST["cust_name"]);
global $connection;
$query = "INSERT INTO invoicesub (";
$query.= " cust_name, description, quantity, amount, discount, total";
$query.= ") VALUES (";
$query.= " '{$cust_name}', '{$name}', {$quantity}, {$amount}, {$discount}, {$total_amt}";
$query.= ")";
$result = mysqli_query($connection, $query);
echo "<tr>";
echo "<td>" . $name . "</td>";
echo "<td>" . $quantity . "</td>";
echo "<td>" . "$" . $amount . "</td>";
echo "<td>" . $discount . "%" . "</td>";
echo "<td>" . "$" . $total_amt . "</td>";
echo "</tr>";
}
if ($result){
redirect_to("invoicesubmitfinal.php?cname=$cust_name");
}
}
?>
invoicesubmitfinal.php
<?php
require_once ("includes/db_connection.php");
global $connection;
$name=$_REQUEST['cname'];
$sql1="SELECT sum(amount) as amount, sum(quantity) as quantity, sum(total) as total FROM invoicesub where cust_name=$name";
$result = mysqli_query($connection, $sql1) or die(mysqli_error());
while ($rows = mysql_fetch_array($result)){
echo $rows['amount'];
echo $rows['quantity'];
echo $rows['total'];
}
?>
The Problem: Trying to calculate sum of a total variable which is inside the table invoicesub in the Form Process (2nd page). Trying to make the sum(total) appear in 3rd page which is display_invoice and also get the customer_name in the form process page(2nd page). somehow $_get["$cust_name"]; is not working and im getting a blank from it. Next, after i can get the sum_total variable how do i parse all these to the 4th page using a form?
Edit:http://imageshack.com/a/img19/8729/btls.png (picture of output)
http://imageshack.com/a/img20/8744/s3ut.png (picture of my database)
Too low rep, i cant post images. I uploaded it to image shack. The 1 on top of the table is from the mysqli_num_rows. This is the first row i entered in the form page. The 2nd row is missing
edit:
New Invoicefinal
echo "<table border='1'>\n";
echo "<tr>\n";
echo "<th>Services Rendered</th>\n";
echo "<th>Quantity</th>\n";
echo "<th>Price($)</th>\n";
echo "<th>Discount(%)</th>\n";
echo "<th>Amount</th>\n";
echo "</tr>";
$cname = $_GET["cname"];
global $connection;
$sql1="SELECT description,quantity, amount, discount, total, SUM(total) as sumtotal FROM invoicesub WHERE cust_name='$cname' GROUP BY description ORDER BY id";
$result2 = mysqli_query($connection, $sql1) or die(mysqli_error($connection));
echo $count;
while ($rows = mysqli_fetch_array($result2)){
echo "<tr>";
echo "<td>" . $rows['description'] . "</td>";
echo "<td>" . $rows['quantity'] . "</td>";
echo "<td>" . $rows['amount'] . "</td>";
echo "<td>" . $rows['discount']. "%" . "</td>";
echo "<td>" ."$". $rows['total'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
<?php
$sql1="SELECT SUM(total) as total_amt FROM invoicesub WHERE cust_name='$cname'";
$result3 = mysqli_query($connection, $sql1) or die(mysqli_error($connection));
while ($rows = mysqli_fetch_array($result3)){
echo "<tr>";
echo "<td>". "Total Amount:" ."$". $rows['total_amt'] . "</td>";
echo "</tr>";
echo "<form action=\"4thpage.php\" method=\"POST\">";
echo "<input type=\"hidden\" name=\"total_amt\"/>";
echo "Customer Paid:";
echo "<input type=\"text\" name=\"paid\" value=\"\"/>";
echo "<input type=\"submit\" name=\"submit\" value=\"Submit\"/>";
echo "<input type=\"button\" value=\"Cancel\" onclick=\"window.location='manage_content.php';\"/>";
echo "</form>";
}
The Form: It consists of a form that can allow more than 1 row of inputs, which means i will have more than 2 descriptions, quantity, amount and discount. Thus, i put them inside an array
Form Process: This is the 2nd page, it will take in all the arrays parsed in, make a loop to insert all the inputted variables in the form into the table invoicesub.
Display_invoice: This is the 3rd page, i want to show all the customer_name, descriptions, quantity, amount, total_amt that was keyed into invoicesub and then do a sum(total) and show it at the bottom of the page. I also want to insert the customer_name, sum(total) variable into the fourth page through the form at display_invoice. Is this possible?
Form
function addTextArea(){
count= count+1;
var div = document.getElementById('name');
div.innerHTML += "<div> <input type='text' name='name[]' value='' "+"id=name"+count+"> </div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('quantity');
div.innerHTML += "<div><input type='text' name='quantity[]' value ='' "+"id=quantity"+count+"></div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('amount');
div.innerHTML += "<div><input type='text' name='amount[]' value ='' "+"id=amount"+count+"></div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('discount');
div.innerHTML += "<div><input type='text' name='discount[]' value ='' "+"id=discount"+count+"></div>";
div.innerHTML += "\n<br />";
}
function removeTextArea(){
document.getElementById("name"+count).remove();
document.getElementById("quantity"+count).remove();
document.getElementById("amount"+count).remove();
document.getElementById("discount"+count).remove();
count = count-1;
}
</script>
</head>
<body>
<form action="invoiceprocess.php" method="POST">
<?php
echo "<table border='2'>\n";
echo "<tr>\n";
echo "<th>Description</th>\n";
echo "<th>Quantity</th>\n";
echo "<th>Amount($)</th>\n";
echo "<th>Discount(%)</th>\n";
echo "</tr>";
echo "<tr>";
echo "<td>"?><input type='text' size="50" name='name[]' value='Examination and Consultation' readonly/><?php "</td>";
echo "<td>"?><input type='text' size="50" name='quantity[]' value='' /><?php "</td>";
echo "<td>"?><input type='text' size="50" name='amount[]' value='' /><?php "</td>";
echo "<td>"?><input type='text' size="50" name='discount[]' value='' /><?php "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>"?><div id="name"></div> <?php "</td>";
echo "<td>"?><div id="quantity"></div> <?php "</td>";
echo "<td>"?><div id="amount"></div> <?php "</td>";
echo "<td>"?><div id="discount"></div> <?php "</td>";
echo "</tr>";
?>
Customer Name:
<br />
<input type="text" name="cust_name" value="" />
<br />
<input type="button" value="Add Description" onClick="addTextArea();">
<input type="button" value="Remove Description" onClick="removeTextArea();">
<input type="submit" name="submit" value="submit">
</form>
</body>
invoiceprocess (The 2nd page)
if (isset($_POST['submit'])){ // Process the form
$name_array = $_POST['name'];
$quantity_array = $_POST['quantity'];
$amount_array = $_POST['amount'];
$discount_array = $_POST['discount'];
$cust_name_array = mysql_prep( $_POST['cust_name']);
for ($i = 0; $i < count($name_array); $i++){
$cust_name = $cust_name_array;
$name = $name_array[$i];
$quantity = $quantity_array[$i];
$amount = $amount_array[$i];
$discount = $discount_array[$i];
$total_amt = ($amount - ($amount * ($discount / 100))) * $quantity;
global $connection;
$query = "INSERT INTO invoicesub (";
$query.= " cust_name, description, quantity, amount, discount, total";
$query.= ") VALUES (";
$query.= " '{$cust_name}', '{$name}', {$quantity}, {$amount}, {$discount}, {$total_amt}";
$query.= ")";
$result = mysqli_query($connection, $query);
}
redirect_to("invoicesubmitfinal.php?cname=".urlencode($cust_name));
}
Display_Invoice(invoicesubmitfinal.php)
echo "<table border='1'>\n";
echo "<tr>\n";
echo "<th>Customer_name</th>\n";
echo "<th>Description</th>\n";
echo "<th>Quantity</th>\n";
echo "<th>Amount($)</th>\n";
echo "<th>Discount(%)</th>\n";
echo "<th>Total_amt</th>\n";
echo "</tr>";
$cust_name = $_GET["$cust_name"];
global $connection;
$sql1="SELECT SUM(total) FROM invoicesub WHERE cust_name='$cust_name'";
$result2 = mysqli_query($connection, $sql1) or die(mysqli_error($connection));
while ($rows = mysqli_fetch_array($result2)){
echo "<tr>";
echo "<td>" . $rows['quantity'] . "</td>";
echo "<td>" . $rows['amount'] . "</td>";
echo "<td>" . $rows['discount']. "%" . "</td>";
echo "<td>" ."$". $rows['total'] . "</td>";
echo "<td>" . "$" . $total_amt . "</td>";
echo "</tr>";
<form action="insertfinal.php" method="POST">
Customer Paid:
<input type="text" name="paid" value="" />
</form>
I am required to create a drop down box which gathers the records from a database to populate the drop down. When one of the values is selected, a form is to be displayed which contains the data relating to the value selected.
The form is to have the function of showing the selected data, but also to update the record in the database when filled out and Submit.
I have created a php file to try and accomplish this, but Im getting errors such as undefined index and unknown column.
I am only new to PHP so this is a big task for me. Could someone have a look at my code and inform me if there are any errors.
Ive been trying to piece code together here and there from the net but its been tricky trying to get it all to work.
I am not getting any errors now after some tweaking, but the record wont update. I get a 'record updated successfully' message but the record isn't updated.
I am pretty sure the lack of a record update is coming down to the ID not getting collected properly via the $q=$row["BearId"] but if I use $q=$_GET["q"] I get nothing but errors. I am not completely positive this is the problem though, that is why Im asking the question here.
I would appreciate any help that you can give. Ive gotten so far with this thing and yet I cant get it to update the record.
EDIT: I have pinpointed the problem down to the id in
$sql = "UPDATE //snip WHERE BearId = '$q'";
$q=$row["BearId"];
If I manually change BearId to equal '1' then the record is updated.
updatebears.php
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Update Bears</title>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("result").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getvalues.php?q="+str,true);
xmlhttp.send();
}
</script>
<style>
// style elements
</style>
</head>
<body>
<h1>Update Bears</h1>
Select a Bear:
<br />
<select name="bears" onchange="showUser(this.value)">
<option value="">Select a BearId</option>
<?php
$query = "SELECT * FROM bears";
$mysqli = new mysqli('localhost','User','123','bears');
$result = $mysqli->query($query);
while($row = $result->fetch_assoc())
echo '<option value="'.$row["BearId"].'">'.$row["BearId"].'</option>';
?>
</select>
<br />
<?php
$q=$row["BearId"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if(array_key_exists('_submit_check', $_POST))
{
$weight = $_POST['Weight'];
$sex = $_POST['Sex'];
$type = $_POST['Type'];
$colour = $_POST['Colour'];
$breed = $_POST['BreedId'];
$sql = "UPDATE bears SET Weight = '$weight', Sex = '$sex', Type = '$type', Colour = '$colour', Breed = '$breed' WHERE BearId = '$q'";
if($mysqli->query($sql) === TRUE)
{
echo 'Record updated successfully<br />';
}
else
{
echo $sql.'<br />' . $mysqli->error;
}
$mysqli->close();
}
?>
<br />
<div id="result"></div>
<br />
Click here to Visit Task 2 (Insert Bears) | Click here to Visit Task 3 (Display Bears)
</body>
</html>
getvalues.php
<?php
$q=$_GET["q"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if($stmt = $mysqli->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($BearId, $Weight, $Sex, $Type, $Colour, $Breed);
while ($stmt->fetch())
{
echo "<form method='post' name='form1' onsubmit='return validateForm()' action='updatebears.php'>";
echo "<p>";
echo "<label for='BreedId'>BreedId:</label>";
echo "<br />";
echo "<select id='BreedId' name='BreedId' />";
echo "<option value='".$Breed."'>".$Breed."</option>";
echo "<option value='1'>1. Polar</option>";
echo "<option value='2'>2. Brown</option>";
echo "<option value='3'>3. Panda</option>";
echo "</select>";
echo "</p>";
echo "<p>";
echo "<label for='Weight'>Weight(kg):</label>";
echo "<br />";
echo "<input type='text' id='Weight' name='Weight' value='".$Weight."' />";
echo "</label>";
echo "</p>";
echo "<p>";
echo "Sex: ";
echo "<br />";
echo "<label for='M'>Male</label><input type='radio' id='M' value='M' name='Sex'";
if($Sex=='M') echo "checked";
echo "/>";
echo "<label for='F'>Female</label><input type='radio' id='F' value='F' name='Sex'";
if($Sex=='F') echo "checked";
echo "/>";
echo "</p>";
echo "<p>";
echo "<label for='Type'>Type:</label> ";
echo "<br />";
echo "<input type='text' id='Type' name='Type' maxlength='100' value='".$Type."' />";
echo "</p>";
echo "<p>";
echo "<label for='Colour'>Colour:</label>";
echo "<br />";
echo "<input type='text' id='Colour' name='Colour' maxlength='20' value='".$Colour."' />";
echo "</p>";
echo "<p>";
echo "<input type='submit' value='Submit' />";
echo "<input type='reset' value='Reset' />";
echo "<input type='hidden' name='_submit_check' value=1 />";
echo "</p>";
echo "</form>";
}
}
else
{
echo 'Unable to connect';
exit();
}
?>
Thanks for the help.
I believe what you need to do is create a hidden input type for the BearId within the getvalues.php file. That way when your form performs the post you can get the BearId from the post as opposed to trying to get it from the $row['BearId']. I'm fairly certain $row['BearId'] is not the same $row['BearId'] that the user selected when he first goes to the getvalues.php form. Have you tried printing $row['BearId'] to html to verify it's a legitimate value?
if(array_key_exists('_submit_check', $_POST))
{
$id = $_POST['BearId']
$weight = $_POST['Weight'];
$sex = $_POST['Sex'];
$type = $_POST['Type'];
$colour = $_POST['Colour'];
$breed = $_POST['BreedId'];
$sql = "UPDATE bears SET Weight = '$weight', Sex = '$sex', Type = '$type', Colour = '$colour', Breed = '$breed' WHERE BearId = '$id'";
if($mysqli->query($sql) === TRUE)
{
echo 'Record updated successfully<br />';
}
else
{
echo $sql.'<br />' . $mysqli->error;
}
$mysqli->close();
}
?>
<h1>getvalues.php</h1>
<?php
$q=$_GET["q"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if($stmt = $mysqli->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($BearId, $Weight, $Sex, $Type, $Colour, $Breed);
while ($stmt->fetch())
{
echo "<form method='post' name='form1' onsubmit='return validateForm()' action='updatebears.php'>";
echo <input type="hidden" name="BearId" value='".$q."'>
echo "<p>";
echo "<label for='BreedId'>BreedId:</label>";
echo "<br />";
echo "<select id='BreedId' name='BreedId' />";
echo "<option value='".$Breed."'>".$Breed."</option>";
echo "<option value='1'>1. Polar</option>";
echo "<option value='2'>2. Brown</option>";
echo "<option value='3'>3. Panda</option>";
echo "</select>";
echo "</p>";
echo "<p>";
echo "<label for='Weight'>Weight(kg):</label>";
echo "<br />";
echo "<input type='text' id='Weight' name='Weight' value='".$Weight."' />";
echo "</label>";
echo "</p>";
echo "<p>";
echo "Sex: ";
echo "<br />";
echo "<label for='M'>Male</label><input type='radio' id='M' value='M' name='Sex'";
if($Sex=='M') echo "checked";
echo "/>";
echo "<label for='F'>Female</label><input type='radio' id='F' value='F' name='Sex'";
if($Sex=='F') echo "checked";
echo "/>";
echo "</p>";
echo "<p>";
echo "<label for='Type'>Type:</label> ";
echo "<br />";
echo "<input type='text' id='Type' name='Type' maxlength='100' value='".$Type."' />";
echo "</p>";
echo "<p>";
echo "<label for='Colour'>Colour:</label>";
echo "<br />";
echo "<input type='text' id='Colour' name='Colour' maxlength='20' value='".$Colour."' />";
echo "</p>";
echo "<p>";
echo "<input type='submit' value='Submit' />";
echo "<input type='reset' value='Reset' />";
echo "<input type='hidden' name='_submit_check' value=1 />";
echo "</p>";
echo "</form>";
}
}
else
{
echo 'Unable to connect';
exit();
}
I have multiple forms on a single page and all gets redirected to same page when form is submitted but the previously submitted form values disappears when new form is submitted.
I tried using sessions didn't worked for me what else? please help
<script language="javascript">
function row(x,y){
//var len=document.forms[x].name.value;
if(x.value.length >=3)
{
//alert("Message form no> "+y+"will be submited");
document.forms[y].submit();
}
}
</script>
</head>
<body >
<center>
<h2>Database App</h2>
<table>
<tr>
<th><lable>Name :</label></th>
<th><label>E_Id :</label></th>
<th><label>Email :</label></th>
<th><label>Other Info :</label></th></tr>
<tr>
<?php
error_reporting(E_ALL ^ E_NOTICE);
// code check for name in database and if exists,displays in table row
//for($i=0;$i<150;$i++)
//{
//$E_id=array();
if($_POST){
$i = $_GET["uid"];
//echo "fhwefwej==".$i;
$x='name'.$i;
// echo 'dasvds'.$x;
if($_POST[$x])
{
$name = strtolower($_POST[$x]);
$E_id[$i] = "";
$Email[$i] = "";
$Otherinfo[$i] = "";
$con = mysql_connect('localhost','root','') or die("npt");
$db = mysql_select_db("trainee")or die("nptdff");
$query = "Select * from reguser where fname like '".$_POST[$x]."%'";
$result = mysql_query($query);
mysql_num_rows($result);
if(mysql_num_rows($result)>0)
{
while($row=mysql_fetch_array($result))
{
$str=$row['fname'];
$initials = strtolower(substr($str,0,3));
if($name == $initials)
{
//echo "exist"."<br>";
$E_id[$i]= $row['fname'];
$Email[$i]=$row['lastname'];
$Otherinfo[$i]=$row['address'];
break;
}
}
}
else
{
$msg[$i] = "no user with these initials";
}
mysql_close($con);
}
}
for($i=0;$i<150;$i++)
{
//session_start();
//echo session_name($i)."<br>";
echo "<form name='form$i' action='new2.php?uid=$i' method='post'>";
echo "<td><input type='text' name='name$i' id='name$i' onkeyup='row(this,$i);' /><br />";
echo "<span id='availability_status' >";
if($_POST[$x]){echo $msg[$i];}
echo "</span> </td>";
echo "<td><input type='text' name='E_id' id='E_id' value='";
if(isset($_POST[$x])){ echo $E_id[$i];}
echo "' disabled='disabled' />";
echo "</td>";
echo "<td><input type='text' name='email' id='email' value='$Email[$i]' disabled='disabled' />";
echo "</td>";
echo "<td><input type='text' name='otherinfo' id='otherinfo' value='$Otherinfo[$i]' disabled='disabled' />";
echo "</td></tr>";
echo " </form>";
}
//echo '<script language="javascript">document.getElementById(\'name0\').focus();</script>';
?>
</table>
</center>
</body>
</html>
Why don't you Use AJAX. It will help to keep you posed different form information in back-end
you can either store those information in database or in file.
It will be the best way.