0

So here is the situation. I have a program that takes data from an array and displays it on a table. I created text input types that allows a client to input new items and when the submit button is clicked, all fields are added to the table. I was thinking if there was a way to write the arrays to the text file and do a fwrite to write the clients input to the text file. Also I notice that the text file keeps getting overwritten so the data inputted would not retain, instead of

$handle=fopen($myfile, "w");

should I use

$handle=fopen($myfile, "a");

Would amend work if no file exists and it will create the text if its not there?

When I run the code I partially borrowed and created, the clients new table is not added to the already existing table.

Sorry if this is unclear, I am a novice. Any help would greatly be appreciated and if you need more information please let me know.

Here is the code I have developed so far:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>

        <center>

        <?php
        $myfile = "file1.txt";
            if(!empty($_POST['product_name']))
            {
         $newData=nl2br(htmlspecialchars($_POST['ta']));
         //////////////////////////////////////////////////

//the following variables are grabbing specific information from the form.
$product_name = array($_POST['product_name']); 
$product_descriptoin = array($_POST['product_description']);
$price = array($_POST['price']);
$image = array($_POST['image']);


    echo '<table border="1" align="center" cellpadding="10">'; 
    echo "<tr align='center'>
            <td><b>Product Name</b></td>
            <td><b>Product Description</b></td>
            <td><b>Price</b></td>
            <td><b>Image</b></td>
          </tr>"; 
foreach ($product_name as $key=>$newData) //this is suppose to add client input
    //to a table.
    {                
        echo "<tr align='center'>";
            echo '<td>';
            echo $product_name[$key];
            echo '</td>';            
            echo '<td>';
            echo $product_descriptoin[$key];
            echo '</td>';           
            echo '<td>';
            printf('$%', $price); 
            echo $price[$key];
            echo '</td>';          
            echo '<td>';
            echo "<img src='".$image[$key]."' width='200' height='300' align='center'>";
            echo '</td>';
     } 
            echo '<tr>';
            echo '<td>';
            echo '<td>';
            echo '<td>';
            echo '<td>';
            echo '</td>';
            echo '</td>';
            echo '</td>';
            echo '</td>';
            echo '</tr>';
     echo '</table>';


         // /////////////////////////////////////////////
         $handle=fopen($myfile, "w");
         fwrite($handle, $newData);
         fclose($handle);
        }
        ?>
        <?php
        if (file_exists("$myfile"))
        {
            $myData= file_get_contents($myfile);
        }


        ?>

        <form action ="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
               <input type="hidden" name="MAX_FILE_SIZE" value="10000000000000" />
    <h1>Product Information Page</h1>
    <p>Product Name: <input type="text" name="product_name" /></p>
    <p>Upload Product Image: <input type="text" name="image" id="image"</p>
    <p>Description: <input type="text" name="product_description" /></p>
    <p>Price: <input type="text" name="price" /></p>


            <br/><br/>
            <input name="submit_btn" type="submit" />
        </form>
        <br/>
        <br/>
        <br/>
        <?php echo $myData; ?>
        <?php
      //Orlando's mini assignment 3
    //arrays that include pictures and all information
$product1 = array('Product Name'=> 'Beauty Boxer Shorts', 'Product Image'=>'<img src= 001.jpg height="88" width="110">', 'Description' => 'Beauty Boxer Shorts', 'Price (each)' => '$14.95');
$product2 = array('Product Name'=> 'Girl Generation Shorts', 'Product Image'=>'<img src= 002.jpg height="88" width="110">', 'Description' => 'Girl Generation Shorts', 'Price (each)' => '$15.95');
$product3 = array('Product Name'=> 'Pick Shorts', 'Product Image'=>'<img src= 003.jpg height="88" width="110">', 'Description' => 'Pick Shorts', 'Price (each)' => '$22.95');
$product4 = array('Product Name'=> 'Red Bull Shorts', 'Product Image'=>'<img src= 004.jpg height="88" width="110">', 'Description' => 'Red Bull Shorts', 'Price (each)' => '$24.95');
$product5 = array('Product Name'=> 'White with Gold <br> Dragon Shorts', 'Product Image'=>'<img src= 005.jpg height="88" width="110">', 'Description' => 'White with Gold <br> Dragon Shorts', 'Price (each)' => '$25.95');
// array of all products
$products = array($product1, $product2, $product3, $product4, $product5);
//setup an html table
echo "<table border=1>";

//prints the table header
echo "<tr>";
$header = array_keys($product1);
foreach ($header as $key => $head)
{
    echo "<th>$head</th>";
}
echo "</tr>";

//iterate through the table body, printing each row
for($i=0; $i<count($products); $i++)
{
    echo "<tr>";
    foreach($products[$i] as $key => $value)
    {
     echo ("<td><center>$value</center></td>");   
}
echo "</tr>";
}

?>
    </body>
</html>
</center>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

2

If you must use a text file instead of a database, then your best approach would be to append the table row data to the file in CSV format.

The first part of your script should handle the form input, preferably validating each field, but in the simplest form, you can create an array from the POSTed data. Then you can use fputcsv() to write to the file, and fgetcsv() to get the CSV data into an array so you can display it in the table.

<?php

/**
 * Ensure you have the full path to the file on the file system
 */
$myFile = dirname(__FILE__).DIRECTORY_SEPARATOR.'file.txt';

/**
 * This section handles the form submit
 */

// Create a boolean value checking the necessary data is posted
$check = isset(
  $_POST['product_name'],
  $_POST['product_description'],
  $_POST['price'],
  $_POST['image']
);
// Do we have the data?
if ($check) {

  // Open the file to append a new row
  $fh = fopen($myFile, "a");

  // Create an array of data from the POSTed vars
  $dataRow = array(
    $_POST['product_name'],
    $_POST['product_description'],
    $_POST['price'],
    $_POST['image']
  );

  // Write the data to file in CSV
  fputcsv($fh, $dataRow);

  // Close the file
  fclose($fh);

}

/**
 * Then we re-open the file for reading
 */
$fh = fopen($myFile, "r");

/**
 * The next section displays the table
 */
?>
  <!DOCTYPE html>
  <html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
  </head>
  <body>

  <form action="/" method="post">
    <p>
      <label for="product_name">Product Name</label>
      <input id="product_name" name="product_name" type="text"/>
    </p>
    <p>
      <label for="product_description">Product Description</label>
      <input id="product_description" name="product_description" type="text"/>
    </p>
    <p>
      <label for="price">Price</label>
      <input id="price" name="price" type="text"/>
    </p>
    <p>
      <label for="image">Image</label>
      <input id="image" name="image" type="text"/>
    </p>
    <input type="submit" value="Submit"/>
  </form>

  <table border="1" align="center" cellpadding="10">
    <tbody>
    <thead>
    <tr>
      <th>Product Name</th>
      <th>Product Description</th>
      <th>Price</th>
      <th>Image</th>
    </tr>
    </thead>
    <tbody>
    <?php
    /**
     * Here you can loop through each row in the file, getting an array of
     * data from the CSV values
     */
    $data = fgetcsv($fh);

    ?>
    <?php while (($data = fgetcsv($fh)) !== false) : ?>
      <tr>
        <td><?php echo htmlentities($data[0]); ?></td>
        <td><?php echo htmlentities($data[1]); ?></td>
        <td><?php echo htmlentities($data[2]); ?></td>
        <td><?php echo htmlentities($data[3]); ?></td>
      </tr>
    <?php endwhile; ?>
    </tbody>
    </tbody>
  </table>

  </body>
  </html>
<?php
/**
 * Finish off by closing the file
 */
fclose($fh);
?>
MarkOK
  • 21
  • 2
  • thanks, trying out your code now. finding out what goes where. – user2926903 Oct 31 '13 at 10:43
  • Hey MarkOK, I am sorry but I am very novice at php and this code when ran does an infinite loop. Any way of showing me locations of input, I am confused on what string is seeing what and from where. Sorry. thanks. – user2926903 Oct 31 '13 at 10:50
  • Sorry Mark, thanks for all your work and efforts. However, because I am a novice I am still not quite sure how to apply this code to my own. Is there a particular order to put them in and is there variables that need to be defined, etc. – user2926903 Oct 31 '13 at 16:53