简体   繁体   中英

How would you tackle this php/mysql

I am building a dynamic (food) menu system for a website. Users will be able to add and remove menu items as they like and alter price etc. If the menus were static then I would have a static form for example

<form id="order_form" action="order.php" method="POST" class="form">
<ul>
<li>cheese burger<input type="text" name="cheese_burger_items" /></li>
<li>bacon burger<input type="text" name="bacon_burger_items" /></li>
<li>steak burger<input type="text" name="steak_burger_items" /></li>
<li>fish burger<input type="text" name="fish_burger_items" /></li>
<li>lamb burger<input type="text" name="lamb_burger_items" /></li>
<input type="submit" value="Submit" />
</form>

Then the order.php would start out like

<?php
$cheese_burger_items = $_POST['cheese_burger_items'];
$bacon_burger_items = $_POST['bacon_burger_items'];
$steak_burger_items = $_POST['steak_burger_items'];
$fish_burger_items = $_POST['fish_burger_items'];
$lamb_burger_items = $_POST['lamb_burger_items'];
?>

This is obviously a grossly simplistic view of it.

The amount of items would vary also. What would be the dynamic approach to doing this? I guess for the input 'name' I could use the index name in the database but that doesn't really help me in order.php as I will need to have a POST for each uniqe item.

I'd build a array of post values and take advantage of php's [] option in input names.

<html>
    <li>
        Cheese Burgers
        <input name='itemID[]' type='hidden' value='$itemID' />
        <input name='itemCount[]' type='text' value='' />  
    </li>
</html>

Then you on the php side you could match itemID[0] with itemCount[0]

If this could represent your menu item (the properties would be set from your database):

$item->id = 'burger';
$item->title = 'Burger';
$item->description = 'This is our plain burger. Why would you buy just this?';

Then an array of those could represent the menu.

echo $menu[0]->id; //'burger';
echo $menu[1]->id; //'cheeseburger';

At that point, the order form is essentially:

<?php foreach($menu as $item): ?>
<li><?php echo $item->title ?> 
    <input type='text' name='order[items][<?php echo $item->id ?>][amount]'>
    <span><?php echo $item->description ?></span>
</li>
<?php endforeach; ?>

And you have a nice representation of it as:

echo $_POST['items']['burger']['amount']; //1

Of course this is a simplistic example, that certainly could be expanded upon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM