0

我的项目在开始 PHP 课程时遇到了问题,这里的标准是:使用 PHP,允许通过网页将任意数量的产品添加到您的在线商店(而不是手动编辑代码或文件)。至少,您应该为每个新产品添加其名称、描述、图像和价格。

添加每个产品后,将修改后的产品列表显示到表格中。产品列表应保存到文件中,以便在您下次访问在线商店时显示更新的库存。

所以我已经制作了用户可以填写的表单,对我来说令人困惑的部分是在用户点击提交之后。我只是不知道如何将“文件”合并到我的代码中,以使其符合我的项目标准(允许用户“添加”信息而无需调整代码或文件)。再次,提前感谢您,非常感谢您的帮助。

Here is my index.php (form)

    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
       <form enctype="multipart/form-data" action="display.php" method="POST">
       <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
    <h1>Product Information Page</h1>
    <p>Product Name: <input type="text" name="product_name" /></p>
    <p>Product Description: <input type="text" name="product_description" /></p>
    <p>Price: <input type="text" name="price" /></p>
    <p>Upload Product Image: <input type="file" name="file" id="file"</p>
    <p><input type="submit" value="submit" /></p>
        </form>


        <?php

        ?>
    </body>
</html>

这是我的 display.php

<?php

$productFile = "file.txt";
if(!empty($_POST['product_name']))
//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['file']);


    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=>$display) 
    {                
        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>';


$ourFileName = "file.txt";
$ourFileHandle = fopen($ourFileName, 'a') or die("can't open file");
fclose($ourFileHandle);
?>
4

1 回答 1

0

这是我得到的代码,让我们看看它是否适合你。

这是在“index.php”页面上

<?php
/* Author: Rick Kazman
 * Created: 11/1/2008
 * Modified: 10/28/2013 to allow data file to be stored in current folder
 * Description: This program displays a table of products and allows products to be added to
 * the online store. The new product contains a product number, description, image, and price.
 */
include "functions.inc"; 

// Useful variables
$datafile = "products.dat";
if (!isset($errors)) $errors = array();

/********************************************
 * Populate and update the array of products.
 ********************************************/
if (array_key_exists("add_item", $_POST))
{
    // If the user has added an item, validate it.  If valid, add it to the array
    $products = arrayfile_to_array($datafile);
    $new_item = $_POST['new_item'];
    $errors = validate_price($errors, $new_item['price']);
    $errors = validate_product($errors, $new_item['prodNum'], $products);
    if (count($errors) == 0)                   // Only add the item if there are no errors
    {
        $products[] = $new_item;
        unset($_POST['new_item']);
    }
    array_to_arrayfile($products, $datafile);  // Rewrite the data file
}
else if (array_key_exists("delete_item", $_POST))
{
    // If the user has added an item, add it to the array and save the file
    $products = arrayfile_to_array($datafile);
    $selected = $_POST['to_del'];
    $size = count($products);

    // Find all the products selected for deletion and remove them
    for ($i=0; $i < $size; $i++)
    {
        if (isset($selected[$i]) && $selected[$i] == "on")  unset($products[$i]);
    }

    $products = array_values($products);       // Reorder the array
    array_to_arrayfile($products, $datafile);  // Rewrite the array file
}
else
{
    if (!file_exists($datafile))  // Data file doesn't exist, so create it
    {
/*      $product1 = array('prodNum' => 'P1221',
                      'description' => 'Double Bubble Windscreen',
                      'image' => 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcT9B6kGG3G1q1Ag1bqPI0ERrNgCaO8aeQxOhvtuStpNDBs-8smK',
                      'price' => 50);
        $product2 = array('prodNum' => 'P1346',
                      'description' => 'Michelin Pilot Power 2ct Set',
                      'image' => 'http://www.motorcycletoystore.com/sport/images/uploads/power2t.jpg',
                      'price' => 300);
        $product3 = array('prodNum' => 'P2094',
                      'description' => 'Scotts Steering Damper',
                      'image' => 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTwTD43wbFLr9vCP36C1ANaq-6bSI3XoU9N8IIUdkbGVw1pz7_UBA',
                      'price' => 350);
        $product4 = array('prodNum' => 'P3942',
                      'description' => 'Frame Slider',
                      'image' => 'http://fstg.motosport.com/motographics/images/products/Metric/07body/LP_CarbonInlaySlider.jpg',
                      'price' => 100);
        $product5 = array('prodNum' => 'P8055',
                      'description' => 'Yoshimura Exhaust',
                      'image' => 'http://www.motorcycle-superstore.com/ProductImages/300/0000_Yoshimura_TRC_Slip-On_Exhaust.jpg',
                      'price' => 850);
        $products = array($product1, $product2, $product3, $product4, $product5); */
                $products = array();
        array_to_arrayfile($products, $datafile);
    }
    else
    {
        $products = arrayfile_to_array($datafile);
    }
}
/***************************
 * Display the product array
 ***************************/
?>

<form method='POST' action='<?php $_SERVER["PHP_SELF"] ?>'>
<h1>Welcome to the MotoStuffe Shoppe!</h1>

<table border =3>
<tr><td><b>Delete?</b></td>
<td><b><center>Product#</center></b></td>
<td><b><center>Product</center></b></td>
<td><b><center>Description</center></b></td>
<td><b><center>Price</center></b></td><tr>

<?php
foreach ($products as $key => $product)
{
    // Print each table row: Product#, Product image, Description, Price
    $prodNum = $product['prodNum'];
    $image = $product['image'];
    $price = sprintf("$%.2f", $product['price']);
    $desc = $product['description'];
    echo "<tr><td><center><input type=Checkbox name=to_del[$key]></center></td><td><center>$prodNum</center></td>" .
         "<td><center><img height=150 src=$image></center></td><td><center>$desc</center></td><td><center>$price</center></td></tr>";
}
?>
</table>
<!-- Get user input / report errors / make forms "sticky" -->

<table>
<tr><td>Product#:</td><td><input type='text' name='new_item[prodNum]'
    value= "<?php  if(isset($_POST['new_item'])) {$tmp = $_POST['new_item']; echo $tmp['prodNum']; } ?>" >
    <?php if (isset($errors['product'])) echo " <font color='red'>{$errors['product']}</font>"; ?></td></tr>
<tr><td>Image:</td><td><input type='text'  name='new_item[image]'
    value= "<?php  if(isset($_POST['new_item'])) {$tmp = $_POST['new_item']; echo $tmp['image']; } ?>"  ></td></tr>
<tr><td>Description:</td><td><input type='text' name='new_item[description]'
    value= "<?php  if(isset($_POST['new_item'])) {$tmp = $_POST['new_item']; echo $tmp['description']; } ?>"  ></td></tr>
<tr><td>Price:</td><td><input type='text' name='new_item[price]'
    value= "<?php  if(isset($_POST['new_item'])) {$tmp = $_POST['new_item']; echo $tmp['price']; } ?>"  >
    <?php if (isset($errors['price'])) echo " <font color='red'>{$errors['price']}</font>"; ?></td></tr>

<tr><td><input type="submit" value="Delete Item(s)" name="delete_item"></td>
    <td><input type="submit" value="Add Item" name="add_item"></td></tr>
</table></form>
<?php $errors = array(); // Clear the errors array  
?>

这是在名为“functions.inc”的第二页上

<?php

// Useful functions
// Created by: Rick Kazman
// Creation date: October 31, 2013

function array_to_arrayfile($theArray, $filepath)
{
    // This function serializes an array in $theArray and saves it
    // in the file at $filepath. The file may then be converted
    // back into an array using the arrayfile_to_array() function)
    if ($fp = fopen($filepath, "w+"))
    {
        $encoded = serialize($theArray);
        fwrite($fp, $encoded);
        fclose($fp);
    }
    else
        echo "Unable to write array to $filepath";
}

function arrayfile_to_array($filepath)
{
    // This function reads the file at $filepath and returns an
    // array. It is assumed that the file being read is a
    // serialized array (created using array_to_arrayfile)†
    $fsize = @filesize($filepath);
    if ($fsize > 0)
    {
        $fp = fopen($filepath, "r");
        $encoded = fread($fp, $fsize);
        fclose($fp);
        return unserialize($encoded);
    }
    else
        echo "$filepath does not exist!";
}


function validate_price($errors, $value)
{
    if( !is_numeric($value) || $value - round($value, 2) != 0 || $value <= 0 )
    {
         $errors['price'] = "Invalid price -- please re-enter";
    }
    return $errors;
}

function validate_product($errors, $prodID, $products)
{
    foreach ($products as $key => $aProduct)
    {
        if ($prodID == $aProduct['prodNum'])  // If the product ID already exists, reject it
        {
            $errors['product'] = "Invalid product ID -- please re-enter";
            break;
        }
    }
    return $errors;
}

?>
于 2013-11-02T09:30:03.813 回答