?
Solved

Displaying inventory of a flat file with a PHP script

Posted on 2009-04-07
7
Medium Priority
?
499 Views
Last Modified: 2013-12-13
I am a week into PHP so forgive my ignorance. I have attached an image of what I am trying to do with a PHP script. I cannot use a database at this point. I have a text file that is comma delimmeted that is known as the inventory. I need to use a PHP script to read this information in a particular format and order on the screen as the "live" inventory we have on hand. Then the customer will select how many of each item they want and this will reduce each inventory item by that quantity. I have an image of what it needs to look like that is coded with HTML but I need to find out how to do it with PHP code. I understand that I will probably use a file pointer and  fopen($inventory.txt, "a+") but how do I get it to print in the correct order? How do I display an array from a text file and can I save an array to a text file?
phpInventory.png
0
Comment
Question by:mhorner0224
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 5

Expert Comment

by:burningmace
ID: 24100862
You can get the entire contents of a text file using file_get_contents() [ http://uk.php.net/file_get_contents ]. You can split the file into arrays using explode() [ http://uk.php.net/explode ]. You can display the results on a page in a format of your choice. You can also open the file, manipulate the values, then write it back with file_put_contents(). I'll warn you that this is a very very bad way to do things - you should use a database. I could fill your page with fake products (i.e. deface your site) with little effort using this method. However, I've written some code to roughly do what you want. See below.
<?php
/*--- Reading the inventory ---*/
$inv = file_get_contents("inventory.txt");
/*
Split the file into lines. On a windows machine you may need ot replace \n with \r, \r\n or \n\r - I forget which.
*/
$lines = explode("\n", $inv);
/* Print out the form code. The hidden value allows the processorder.php script to know how many quantity values it needs to read. */
echo '<form action="processorder.php" method="POST">
<inpur type="hidden" name="count" value="' . count($lines) . '" />';
/* Iterate through each line */
for($l = 0; $l < count($lines); $l++) {
	/* Split the line out into values (separator is a comma) */
	$vals = explode(",", $lines[$i]);
	/* Column 0 is name, 1 is stock, 2 is price */
	$name = $vals[0];
	$stock = $vals[1];
	$price = $vals[2];
	/* Show the product info */
	echo "Product Name: {$name}<br />Price: {$price}<br />Quantity in Stock: {$stock}<br />";
	/* Now show the text box for order quantity for this particular product */
	echo 'Quantity: <input type="text" name="order_' . $l . '" value="0" /><br /><br />';
}
echo '</form>';
?>
 
<?php
/*--- processorder.php ---*/
/* All values posted by the form are put into the $_POST[] array. */
$count = $_POST['count'];
/* Read the inventory */
$inv = file_get_contents("inventory.txt");
$lines = explode("\n", $inv);
for($i = 0; $i < $count; $i++) {
	/* Get the quantity the user wants to order */
	$qty = $_POST["order_{$i}"];
	if($qty > 0) {
		/* Split out the line */
		$vals = explode(",", $lines[$i]);
		/* vals[1] is the second column, i.e. the price */
		if($vals[1] < $qty) {
			echo "You cannot order {$qty} of product '{$vals[0]}' - there are only {$vals[1]} in stock!<br />";
		} else {
			/* Decrease quantity by amount ordered */
			$vals[1] -= $qty;
			/* implode is the opposite of explode - it sticks them back together */
			$lines[$i] = implode(",", $vals);
			echo "{$qty} of product '{$vals[0]}' ordered.<br />";
		}
	}
}
/* All $lines entries are updated with new values */
/* Now stick them back together */
$ft = implode("\n", $lines);
file_put_contents("inventory.txt", $ft);
?>

Open in new window

0
 
LVL 5

Expert Comment

by:burningmace
ID: 24100927
Just to expand on the security problem I mentioned above...

Consider what would happen if I sent a request to the script with post variables of count=80000 when there were 7 products. To put it simply, you'll get a big page full of errors and empty product entries. I'll leave it to you to find a solution, otherwise it's no fun - remember that the $lines array can be counted.
0
 

Author Comment

by:mhorner0224
ID: 24103418
Thank you. Do I need to separate the <form> from the PHP code? When I go to add a submit button it gives me a parse error. Additionally it will not display the items in the array from the text file. Any ideas?
0
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 

Author Comment

by:mhorner0224
ID: 24103700
I found the problem with not displaying the items in the array.

It had:  $vals = explode(",", $lines[$i]);
Replaced with:  $vals = explode(",", $lines[$l]);

I'll keep working on it.
0
 
LVL 5

Accepted Solution

by:
burningmace earned 1500 total points
ID: 24106122
Sorry, I have a habit of mixing up $l and $i in code... I've been stuck with a 17" screen that's 4ft from my chair recently, not the easiest thing to read from ^_^

If you need any more help just let me know.
0
 

Author Comment

by:mhorner0224
ID: 24107202
I needed to incorporate some html and customer data fields. I have added this portion but now the question is what's the best way to store the payment information into a transaction file that will append the items, amounts of each purchased and overall cost of the transaction with each transaction? Would I use an array to do this as well? Additionally I need to display the last individual transaction on the processorder.php page to function as a confirmation page like you are doing with the items now. Can that be added to the current array?

Now that I have attached the additional fields it will not display anything in the processorder.php file. I'll attach both for you to review. I may have gone about combining both the wrong way. Below is my changed code. Thanks for any suggestions.
<!-- order.php --->
<html>
<head>
	<style type="text/css">
<!--
body {
	background-color: #80030e;
}
a:link {
	color: #FFF;
	text-decoration: none;
}
a:visited {
	text-decoration: none;
}
a:hover {
	text-decoration: underline;
}
a:active {
	text-decoration: none;
}
body,td,th {
	color: #FFF;
}
-->
</style>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head>
<body>
<form action="processorder.php" method="POST">
<input type="hidden" name="count" value="' . count($lines) . '" />
<table width ="800" border="1" align="center" cellpadding="0" cellspacing="0">
<tr>
<td>
 
<table width="800" align ="center" cellspacing="0" cellpadding="0" bgcolor"c0c0c0">
	<tr>
		<td colspan="6" align="center"><img src="dr_pepper_logo2.png" width="800" height="221" alt="Dr Pepper Logo"></td>
</tr>
	<tr>
	  <td colspan="6" align="center"><p><strong><a href="resetInventory.php">Refresh the Inventory</a> | <a href="rateme.php">Rate This Site</a> | <a href="login.php">Login</a></strong></p>
      <p>&nbsp;</p></td>
    </tr>
	<tr>
	  <td colspan="6" align="center"><?php
/*--- Reading the inventory ---*/
$inv = file_get_contents("inventory.txt");
/*
Split the file into lines. 
*/
$lines = explode("\n", $inv);
/* Print out the form code. The hidden value allows the processorder.php script to know how many quantity values it needs to read. */
 
/* Iterate through each line */
for($l = 0; $l < count($lines); $l++) {
	/* Split the line out into values (separator is a comma) */
	$vals = explode(",", $lines[$l]);
	/* Column 0 is name, 1 is stock, 2 is price */
	$name = $vals[0];
	$stock = $vals[1];
	$price = $vals[2];
	/* Show the product info */
	echo " Product Name: {$name}<br />Price: {$price}<br />Quantity in Stock: {$stock}<br />";
	/* Now show the text box for order quantity for this particular product */
	echo 'Quantity: <input type="text" name="order_' . $l . '" value="0" /><br /><br />';
}
 
?></td>
    </tr>
	<tr>
	  <td colspan="6" align="center">&nbsp;</td>
    </tr>
<tr>
    <td width="270" align="right"><p><strong>Name:</strong></p></td>
    <td width="17">&nbsp;</td>
    <td width="184"><label>
      <input name="name" type="text" id="name" tabindex="1" size="25" maxlength="25" />
    </label></td>
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr>
    <td align="right"><strong>Address:</strong></td>
    <td>&nbsp;</td>
    <td><input name="address" type="text" id="address" tabindex="2" size="25" maxlength="25" /></td>
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr>
    <td align="right"><strong>City:</strong></td>
    <td>&nbsp;</td>
    <td><input name="city" type="text" id="city" tabindex="3" size="25" maxlength="25" /></td>
    <td width="40" align="right"><strong>State:</strong></td>
    <td width="13">&nbsp;</td>
    <td width="276"><input name="state" type="text" id="state" tabindex="4" size="4" maxlength="2" /></td>
  </tr>
  <tr>
    <td align="right"><strong>Zip Code:</strong></td>
    <td>&nbsp;</td>
    <td><input name="zip" type="text" id="zip" tabindex="5" size="25" maxlength="25" /></td>
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr>
    <td align="right">&nbsp;</td>
    <td colspan="2">&nbsp;</td>
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr>
    <td align="right"><strong>Credit Card Number:</strong></td>
    <td>&nbsp;</td>
    <td><input name="creditcard" type="text" id="creditcard" tabindex="6" size="16" maxlength="16" /></td>
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td colspan="2">&nbsp;</td>
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr>
    <td colspan="6" align="center"><label>
      <input type="submit" name="submit" id="submit" value="Submit" tabindex="7" />
      <br>
    </label></td>
  </tr>
  <tr>
    <td colspan="6" align="center">&nbsp;</td>
  </tr>
</table>
</td>
</tr>
</table>
<br> <br> <br>
</form>
</body>
 
</html>
 
 
<?php
/*--- processorder.php ---*/
/* All values posted by the form are put into the $_POST[] array. */
$count = $_POST['count'];
/* Read the inventory */
$inv = file_get_contents("inventory.txt");
$lines = explode("\n", $inv);
 
for($i = 0; $i < $count; $i++) {
	/* Get the quantity the user wants to order */
	$qty = $_POST["order_{$i}"];
	if($qty > 0) {
		/* Split out the line */
		$vals = explode(",", $lines[$i]);
		
		/* vals[1] is the second column, i.e. the price */
		if($vals[1] < $qty) {
			echo "You cannot order {$qty} of product '{$vals[0]}' - there are only {$vals[1]} in stock!<br />";
		} else {
			/* Decrease quantity by amount ordered */
			$vals[1] -= $qty;
			/* implode is the opposite of explode - it sticks them back together */
			$lines[$i] = implode(",", $vals);
			echo "{$qty} of product '{$vals[0]}' ordered.<br />";
		}
	}
}
/* All $lines entries are updated with new values */
/* Now stick them back together */
$ft = implode("\n", $lines);
file_put_contents("inventory.txt", $ft);
?>
 

Open in new window

0
 

Author Closing Comment

by:mhorner0224
ID: 31567852
Thanks for your help.
0

Featured Post

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

650 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question