Link to home
Start Free TrialLog in
Avatar of jspc
jspcFlag for Australia

asked on

PHP File in HTML

Hello

I have an Order HTML page where a User can enter data into fields.  On Submit PHP file is used to write the data to SQL Tables called Orders and Orders_details.

Currently, when l test this I'm getting the below error.
User generated image
Below is my PHP file:
If you need table structures I can provide these too.

The line error is highlighted below.
User generated image===================

<!DOCTYPE HTML>
<html>
<head>
<title>Product_Order</title>
<meta charset="utf-8">

</head>
<body>

<?php

  /* Set oracle user login and password info */
  $dbuser = ;  
  $dbpass = ;  
  $db = ;
  $connect = oci_connect($dbuser, $dbpass, $db);

   /* Display connection error if fails */
  if (!$connect)  {
    echo "An error occurred connecting to the database";
    exit;
  }

  //Extract CGI variables
  $productitem = $_POST['productitem'] ;
  $price = $_POST['price'] ;
  $quantity = $_POST['quantity'] ;
  $firstname = $_POST['firstname'] ;
  $lastname = $_POST['lastname'] ;
  $address = $_POST['address'] ;
  $phone = $_POST['phone'] ;
  $email = $_POST['email'] ;
  $creditcard = $_POST['creditcard'] ;


  // count the record in orders table and use id number $count+1 for the new record
  $query_count = "SELECT max(ID) FROM Orders";

  echo "SQL: $query_count<br>";

  /* check the sql statement for errors and if errors report them */
  $stmt = oci_parse($connect, $query_count);

  if(!$stmt)  {
    echo "An error occurred in parsing the sql string.\n";
    exit;
  }

  oci_execute($stmt);
  if (oci_fetch_array($stmt))  {
      
      $count = oci_result($stmt,1);//returns the data for column 1
      echo $count."</br>";

  } else {
      echo "An error occurred in retrieving order id.\n";
      exit;
  }

  $count++;
echo $count."</br>";

  // Create the SQL statement to add the data
  $query = "INSERT INTO Orders (ID, Firstname, Lastname, Address, Phone, Email, Creditcard) VALUES ($count, '$firstname', '$lastname', '$address', '$phone', '$email', '$creditcard')";

  echo $query
 
  /* check the sql statement for errors and if errors report them */
  $stmt = oci_parse($connect, $query);
  echo "SQL: $query<br>";

  if(!$stmt)  {
    echo "An error occurred in parsing the sql string.\n";
    exit;
  }

  oci_execute($stmt);

  /*
  // count the record in order_details table and use id number $count+1 for the new record

  $query_count_2 = "SELECT max(ID) FROM Order_details";

  //echo "SQL: $query_count_2<br>";

  // check the sql statement for errors and if errors report them
  $stmt_2 = OCIParse($connect, $query_count_2);

  if(!$stmt_2)  {
    echo "An error occurred in parsing the sql string.\n";
    exit;
  }
  OCIExecute($stmt_2);

  $product_1 =0;

  while(OCIFetch($stmt_2))  {

      $product_1 = OCIResult($stmt_2,"ID");

  }

  $product_1 =$product_1 +1; */
 
    $query_count = "SELECT max(ID) FROM Order_details";

  echo "SQL: $query_count<br>";

  /* check the sql statement for errors and if errors report them */
  $stmt = oci_parse($connect, $query_count);

  if(!$stmt)  {
    echo "An error occurred in parsing the sql string.\n";
    exit;
  }

  oci_execute($stmt);
  if (oci_fetch_array($stmt))  {
      
      $product = oci_result($stmt,1);//returns the data for column 1
      echo $product."</br>";

  } else {
      echo "An error occurred in retrieving order id.\n";
      exit;
  }

  $product++;

  $query2 = "INSERT INTO Order_details (ID, order_ID, Product, Price, Quantity, Subtotal) VALUES ($product, $count, '$productitem', '$price', '$quantity', '$subtotal')";

  echo $query2
 
  /* check the sql statement for errors and if errors report them */
  $stmt_2 = oci_parse($connect, $query2);
  echo "SQL: $query2<br>";

  if(!$stmt_2)  {
    echo "An error occurred in parsing the sql string.\n";
    exit;
  }

  oci_execute($stmt_2);

 
  //display a receipt with all the order details

  echo ("<p>Thank you. The order with ID ".$count. " has been received!</p>");
  echo ("<p>Your Order Details are:</p>");
  if ($productitem != 0)
  echo ("<p>Product ". $productitem." Quantity  ".$quantity. ". Price is ". $price." * ".$quantity." = ".$subtotal.".</p>");
  echo ("<p>Total$  ".($subtotal) . "</p>");


  /*
 $query_count_2 = "SELECT * FROM Order_details WHERE Order_ID = '$count'";

  //echo "SQL: $query_count_2<br>";

  /* check the sql statement for errors and if errors report them
  $stmt_2 = OCIParse($connect, $query_count_2);

  if(!$stmt_2)  {
    echo "An error occurred in parsing the sql string.\n";
    exit;
  }
  OCIExecute($stmt_2);

 
  while(OCIFetch($stmt_2))  {
      $test_2 = OCIResult($stmt_2,"ID");
      echo "Order detail ID: ". $test_2."<br><br>";

  } */

// Close the connection
oci_close($connect);
?>

</body>
</html>
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jspc

ASKER

Thanks for that.

You wouldn't know why I'm now getting this would you?
It appears to be writing to the ID but the other fields aren't being populated for some reason.

User generated image
The only thing is can see is that you'r POST array may not be populated (or you have the key names wrong). Try var-dumping it at the top of your script to see what you get:

var_dump($_POST);

//Extract CGI variables
$productitem = $_POST['productitem'] ;
$price = $_POST['price'] ;
...

Open in new window

Avatar of jspc

ASKER

Like this?


  //Extract CGI variables
  $firstname=$_POST['firstname'];
  $lastname=$_POST['lastname'];
  $address=$_POST['address'];
  $phone=$_POST['phone'];
  $email=$_POST['email'];
  $creditcard=$_POST['creditcard'];
  $productitem=$_POST['productitem'];
  $price=$_POST['price'];
  $quantity=$_POST['quantity'];
 
  var_dump($_POST);

//Extract CGI variables
$productitem = $_POST['productitem'] ;
$price = $_POST['price'] ;
...
Yeah - but you only need to set all your own variables once, so this would do it:

  var_dump($_POST);

//Extract CGI variables
  $firstname=$_POST['firstname'];
  $lastname=$_POST['lastname'];
  $address=$_POST['address'];
  $phone=$_POST['phone'];
  $email=$_POST['email'];
  $creditcard=$_POST['creditcard'];
  $productitem=$_POST['productitem'];
  $price=$_POST['price'];
  $quantity=$_POST['quantity'];

Open in new window

All var_dump does is show you what's contained in a variable - the POST array in the above example.
Avatar of jspc

ASKER

I get this ..

User generated image
In that case your POST array is empty so there is nothing to enter into the database. A post array is only populated when you submit a form to a script and that form has the method set to POST, and the fields in your form have a name attribute:

<form method="post" action="someScript.php">
   <input type="text" name="firstName">
   <input type="submit" name="submit" value="Submit">
</form>

Open in new window

If you clicked the submit button, then someScript.php would have the following POST array:

$_POST["firstName"]
$_POST["submit"]
Avatar of jspc

ASKER

Yes, that is what I gave. Please see below:

User generated image
If you look at your code, none of the fields are inside the form. The only 2 fields you have in the form are the submit and reset button and as none of these have names, even they don't get sent to the POST array. All your form fields need to be between the opening <form> tag and the closing </form> tag.
Avatar of jspc

ASKER

Got it!
Awesome. Thank you for your help. Much appreciated.
You're welcome :)
Avatar of jspc

ASKER

Sorry to be a pain - my first line is now working but for some reason, the second is not inserting.
I am also not getting my details appearing in the receipt section.

User generated image
Look at these lines:

$productitem = $_POST['productitem'] ;
$price = $_POST['price'] ;
$quantity = $_POST['quantity'] ;

They imply that your form has fields called productitem, price and quantity. Looking at the form code you just posted, they don't exist

And then your query

$query2 = "INSERT INTO Order_details (ID, order_ID, Product, Price, Quantity, Subtotal) VALUES ($product, $count, '$productitem', '$price', '$quantity', '$subtotal')";

You're trying to insert these non-existent values into your query.

No idea where $subtotal comes from as there's no mention of it anywhere in your code
To help you with all this, you really, really should turn error reporting on in your script. At the very top of your script, add the following:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>

Then all these non-existent values will be errored out to your page. Nearly impossible to code cleanly if you don't have error reporting turned on :)
Avatar of jspc

ASKER

Ok .. I have added your error reporting.

Now I get:

User generated image


Here is my PHP:

==========

<!DOCTYPE HTML>
<html>
<head>
<title>Product_Order</title>
<meta charset="utf-8">

</head>
<body>

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>


<?php 

  /* Set oracle user login and password info */
  $dbuser = "jspeders";  
  $dbpass = "Jspc6472";  
  $db = "SSID"; 
  $connect = oci_connect($dbuser, $dbpass, $db); 

   /* Display connection error if fails */
  if (!$connect)  {
    echo "An error occurred connecting to the database"; 
    exit; 
  }
  
  

  //Extract CGI variables
  $firstname=$_POST['firstname'];
  $lastname=$_POST['lastname'];
  $address=$_POST['address'];
  $phone=$_POST['phone'];
  $email=$_POST['email'];
  $comment2=$_POST['comment2'];
  $creditcard=$_POST['creditcard'];
  $productitem=$_POST['productitem'];
  $price=$_POST['price'];
  $quantity=$_POST['quantity'];
  $comment1=$_POST['comment1'];
  

  // count the record in orders table and use id number $count+1 for the new record
  $query_count = "SELECT max(ID) FROM Orders";

  /* echo "SQL: $query_count<br>"; */

  /* check the sql statement for errors and if errors report them */
  $stmt = oci_parse($connect, $query_count); 

  if(!$stmt)  {
    echo "An error occurred in parsing the sql string.\n"; 
    exit; 
  }

  oci_execute($stmt);
  if (oci_fetch_array($stmt))  {
	
	$count = oci_result($stmt,1);//returns the data for column 1 
	echo $count."</br>";

  } else {
	echo "An error occurred in retrieving order id.\n"; 
	exit; 
  }

  $count++;
	/* echo $count."</br>"; */

  // Create the SQL statement to add the data
  $query = "INSERT INTO Orders (ID, firstname, lastname, address, phone, email, creditcard, comment2) VALUES ($count, '$firstname', '$lastname', '$address', '$phone', '$email', '$creditcard', '$comment2')"; 

  /* echo $query; */
  
  /* check the sql statement for errors and if errors report them */
  $stmt = oci_parse($connect, $query); 
  echo "SQL: $query<br>";

  if(!$stmt)  {
    echo "An error occurred in parsing the sql string.\n"; 
    exit; 
  }

  oci_execute($stmt);

  /*
  // count the record in order_details table and use id number $count+1 for the new record

  $query_count_2 = "SELECT max(ID) FROM Order_details";

  //echo "SQL: $query_count_2<br>";

  // check the sql statement for errors and if errors report them 
  $stmt_2 = OCIParse($connect, $query_count_2); 

  if(!$stmt_2)  {
    echo "An error occurred in parsing the sql string.\n"; 
    exit; 
  }
  OCIExecute($stmt_2);

  $product_1 =0; 

  while(OCIFetch($stmt_2))  {

	$product_1 = OCIResult($stmt_2,"ID");

  } 

  $product_1 =$product_1 +1; */
  
    $query_count = "SELECT max(ID) FROM Order_details";

  /* echo "SQL: $query_count<br>"; */

  /* check the sql statement for errors and if errors report them */
  $stmt = oci_parse($connect, $query_count); 

  if(!$stmt)  {
    echo "An error occurred in parsing the sql string.\n"; 
    exit; 
  }

  oci_execute($stmt);
  if (oci_fetch_array($stmt))  {
	
	$product = oci_result($stmt,1);//returns the data for column 1 
	echo $product."</br>";

  } else {
	echo "An error occurred in retrieving order id.\n"; 
	exit; 
  }

  $product++;

  $query2 = "INSERT INTO Order_details (ID, order_ID, productitem, price, quantity, comment1) VALUES ($product, $count, '$productitem', '$price', '$quantity', '$comment1')"; 

  /* echo $query2; */
  
  /* check the sql statement for errors and if errors report them */
  $stmt_2 = oci_parse($connect, $query2); 
  echo "SQL: $query2<br>";

  if(!$stmt_2)  {
    echo "An error occurred in parsing the sql string.\n"; 
    exit; 
  }

  oci_execute($stmt_2);

 
  //display a receipt with all the order details
	echo ("<p>====================== ORDER DETAILS =============================</p>");
  echo ("<p>Thank you. The order with ID ".$count. " has been received!</p>");
  echo ("<p>Your Order Details are:</p>");
  if ($productitem != 0)
  echo ("<p>Product ". $productitem." Quantity  ".$quantity. ". Price is ". $price." * ".$quantity." = ".$subtotal.".</p>");
  echo ("<p>Total$  ".($subtotal) . "</p>");


  /*
 $query_count_2 = "SELECT * FROM Order_details WHERE Order_ID = '$count'";

  //echo "SQL: $query_count_2<br>";

  /* check the sql statement for errors and if errors report them 
  $stmt_2 = OCIParse($connect, $query_count_2); 

  if(!$stmt_2)  {
    echo "An error occurred in parsing the sql string.\n"; 
    exit; 
  }
  OCIExecute($stmt_2);

 
  while(OCIFetch($stmt_2))  {
	$test_2 = OCIResult($stmt_2,"ID");
	echo "Order detail ID: ". $test_2."<br><br>";

  } */

// Close the connection
oci_close($connect); 
?>

</body>
</html>

Open in new window

When you post up code, it helps if you wrap it in the Code tags (you'll see a code button when you write a comment). I've edited your previous post to do this - it helps as it gives us line numbers to work with.

The error messages tell you exactly what's wrong, and exactly what line the error is on. If you look at the lines in your code that show an error you'll see this:

$comment2=$_POST['comment2'];
$productitem=$_POST['productitem'];
$price=$_POST['price'];
$quantity=$_POST['quantity'];
$comment1=$_POST['comment1'];

The Undefined index 'comment2' means that this doesn't exist:

$_POST['comment2']

As I've already said, if it doesn't exist in your form, then it won't exist in your script. Make sure your form has all the fields that your script needs.

The last error says undefined variable $subtotal, and refers to this line:

 echo ("<p>Total$  ".($subtotal) . "</p>");

Again, I've already pointed out that nowhere in your code do you define and set a variable called $subtotal.

Before using a variable you need to define it and potentially set a value, For example:

$subtotal = 123;
Avatar of jspc

ASKER

My HTML file does have the fields:

User generated image
OK. Post your full HTML file (in Code tags). The form that you've just shown looks very different to the form you posted earlier.
Avatar of jspc

ASKER

It is the same form. That particular section was above, that's all.

Below:

=====================

<!DOCTYPE html>
<html lang="en">
<head>
<style>
h4 {
	background-color: #e1e1d0;
	padding: 5px;
	}
#Footer
	{border: 1px solid black;
	padding: 5px;
	text-align: center;
	}
	
input, textarea {margin-top: 10px;
		margin-bottom: 10px;
		padding: 5px;
		width: 40%;
		}
	
#submit	{margin-left: 5px; 
		padding-right: 12px;}
				
.rad_btn {vertical-align:-5%
	}

#Menu {background-color: #b8bac6;
		padding: 20px;
		}
		
</style>

<title>BooksRUS</title>
<link rel="stylesheet" href="styles2.css" type="text/css">
<meta charset="utf-8">

<script>
/*
This JavaScript is used to check the data validation on each field. 
If one field has been corrected filled in, the script will then move down this list 
until all fields specified are validated and pass the required criteria otherwise 
an alert warning message will be given to the User.
*/
   function validateForm() {
	var quantity = document.forms["myForm"]["quantity"].value;
    var firstname = document.forms["myForm"]["firstname"].value;
    var lastname = document.forms["myForm"]["lastname"].value;
	var address = document.forms["myForm"]["address"].value;
	var phone = document.forms["myForm"]["phone"].value;
	var email = document.forms["myForm"]["email"].value;
	var cardname = document.forms["myForm"]["cardname"].value;
	var creditcard = document.forms["myForm"]["creditcard"].value;
	var expirydate = document.forms["myForm"]["expirydate"].value;
    if (quantity < "0") {
        alert("Book quantity must be greater than zero");
		return false;
     }
		if (firstname == "") {
        alert("First Name must be populated, cannot be blank");
		return false;
     }
	 if (lastname == "") {
        alert("Last Name must be populated, cannot be blank");
        return false;
    }
	if (address == "") 	{
        alert("Address must be populated, cannot be blank");
        return false;
		}
	if (phone == "") {
        alert("Phone must be populated, cannot be blank");
        return false;
		}
	if (email == "") {
        alert("Email must be populated, cannot be blank");
        return false;
		}	
	if (cardname == "") {
        alert("Card Name must be populated, cannot be blank");
        return false;
		}
	if (creditcard == "") {
        alert("Card Number must be populated, cannot be blank");
        return false;
		}	
	if (expirydate == "") {
        alert("Expiry Date must be selected");
        return false;
		}			
    return true;  
}  

 function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
       }
	   
function setPrice() {
  var pi = document.getElementById("productitem");
  var p = document.getElementById("price")
  p.value = pi.options[pi.selectedIndex].getAttribute("data-price");
}

</script>



</head>

<body>



<div id="Container">
	<div id="Header"><h1>BooksRUS</h1>
<h3>Best Secondhand Book Shop in Geelong</h3></div>
	<div id="Menu"><b><a href="index.html">Home</a> | <a href="books.html">Books</a> | <a href="orderbooks.html">Order Books</a> | <a href="faq.html">FAQ</a> | <a href="contact.html">Contact</a></b>
	</div>
	
<div id="MainBody1"><p><h4 style="Color:#3498DB">Order Books</h4></div>

<form action="bookSearch.php" method="get" name="booksearch_LIKE" id="booksearch_LIKE">
	Search a Book: <input type="text" name="book_name" value="Search here... Or blank out field to display all">
	<input type="submit" value="Search">
</form><br>
	
<form action="product_order.php" method="post" name="product_order" id="product_order">		
		
<fieldset>
  <legend>Order Book Details:</legend>

  <label for="productitem">Product Item:</label>
  <br>
  <select name="productitem" id="productitem" autofocus onchange="setPrice()">
    <option value="selection">Make your selection from here ...</option>
    <option data-price="19.00" value="livewellonless">Live Well on Less</option>
    <option data-price="29.99" value="eatrealfood">Eat Real Food</option>
    <option data-price="32.99" value="mylifeitsalongstory">My Life, It's a Long Story</option>
    <option data-price="15.99" value="swordofsummer">Sword of Summer</option>
    <option data-price="12.99" value="clementineroseandthebirthday">Clementine Rose and the Birthday Emergency</option>
    <option data-price="15.99" value="middleschooljustmyrottenluck">Middle School: Just My Rotten Luck</option>
  </select>
  <br>
  <br>

  <label for="price">Price:</label>
  <br>
  <input type="text" id="price" name="price" onkeypress="return isNumberKey(event)">
  <br>

  <label for="quantity">Quantity:</label>
  <br>
  <input type="text" id="quantity" name="quantity" onkeypress="return isNumberKey(event)">
  <br> Comments:
  <br>
  <textarea name="comment1">Please place your comment here ...</textarea>
</fieldset>

<br>



	<div id="MainBody2"><p><h4 style="Color:#3498DB">Customer Delivery Details</h4></div>
	<fieldset>
<legend>Delivery Details:</legend>
		First Name: <br><input type="text" name="firstname" onkeyup="this.value = this.value.replace(/[^A-z]/, '')" /><br>
		Last Name:  <br><input type="text" name="lastname" onkeyup="this.value = this.value.replace(/[^A-z]/, '')" /><br>
		Address:    <br><input type="text" name="address"><br>
		Phone:		<br><input type="text" name="phone" maxlength="10"><br>
		Mobile Phone: <br><input type="text" name="mobilephone" maxlength="10"><br>
		Email:     <br><input type="email" name="email"><br>
		Comments:<br><textarea name="comment2">Please place your comment here ...</textarea>
</fieldset>
					
	<div id="MainBody3"><p><h4 style="Color:#3498DB">Payment Method</h4></div>
	
<fieldset>
<legend>Payment Details:</legend>
		Card Name Holder: 	<br><input type="text" name="cardname" onkeyup="this.value = this.value.replace(/[^ A-z]/, '')" /><br>
		Credit Card Number: <br><input type="text" name="creditcard" maxlength="16" onkeypress="return isNumberKey(event)" ><br>
		Expiry Date:    	<br><input type="date" name="expirydate"><br>
		
		Master Card <br><input type="radio" name="paymethod" id="paymethod3" value="3"><br>
		Visa Card <br><input type="radio" name="paymethod" id="paymethod4" value="4"><br>
		American Express <br><input type="radio" name="paymethod" id="paymethod5" value="5"><br>
		
</fieldset>

		<input type="submit" value="Submit">
		<input type="reset" value="Clear the Form">
</form>
			
	
<div id="Footer"><small><i>"©Deakin University, School of Information Technology. This web page has been developed as a student assignment for the unit SIT104: Introduction to Web Development. Therefore it is not part of the University's authorised web site. DO NOT USE THE INFORMATION CONTAINED ON THIS WEB PAGE IN ANY WAY."</i></small></div>


</body>
</html>

Open in new window

OK. Just tested your html file and all the correct information is being posted. Your post array has all the correct keys, so either something else is going on or you're not using the correct HTML file (several versions / browser cached etc)

Try adding the var_dump($_POST) back into your script and examine that:

var_dump($_POST);

//Extract CGI variables
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$address=$_POST['address'];
...

Open in new window