Foro de elhacker.net

Programación => PHP => Mensaje iniciado por: ^kazike^ en 26 Octubre 2006, 07:22 am



Título: mas problemas con php
Publicado por: ^kazike^ en 26 Octubre 2006, 07:22 am
Hola, sigo con mi carrito, al final lo unico q tengo q hacer es permitir coger los productos de 1 en 1 y poer seleccionar ingredientes. el problema que tengo es que si cojo por ejemplo 2 hamburguesas con disitintos ingredientes me los trata cmo productos iguales y yo quiero q los trate cmo productos distintos y q los liste tb cmo productos distintos.
Os pego el codigo:
Código:
<?php
      2 // start session
      3 session_start();
      4
      5 // initialize session shopping cart if you are connecting for the first time
      6 if (!isset($_SESSION['cart']))
      7 {
      8     $_SESSION['cart'] = array();
      9 }
     10
     11
     12 // Specify the name of the file containing data
     13 $catalogFile = "catalog.dat";
     14 // if file is available, extract data from it
     15 // place into $CATALOG array, with SKU as key
     16 if (file_exists($catalogFile))  //does the file exist
     17 {
     18     $data = file($catalogFile); //read entire file into array. Each line occupies
     19                                 //one array slot. NOT good if file is large.
     20     foreach ($data as $line)
     21     {
     22         $lineArray = explode(':', $line); //lineArray contain three items: SKU,
     23                                           //description, and price
     24         $sku = trim($lineArray[0]);
     25         $CATALOG[$sku]['desc'] = trim($lineArray[1]); //trim removes extra white
     26         $CATALOG[$sku]['price'] = trim($lineArray[2]);//space from either end
     27     }
     28 }
     29 // file is not available
     30 // stop immediately with an error
     31 else
     32 {
     33     die("Could not find catalog file");
     34 }
     35
     36 // check to see if the form has been submitted
     37 // and which submit button was clicked
     38
     39 // if this is an add operation
     40 // add to already existing quantities in shopping cart
     41 if ($_POST['add'])
     42 {
     43     foreach ($_POST['a_qty'] as $k => $v)
     46     {
     47         // if the value is 0 or negative
     48         // don't bother changing the cart
     49         if ($v > 0)                       //occurs if user entered data
     50         {
     51
     52             //i get the ingredients if there are meals selected
     53             if ($k==101)
     54              {
     55                $newstring = "Hamburguer";
     56                foreach ($_POST['ing'] as $o)
     57                 $newstring = $newstring . " " . $o;
     58              }
     59             //line below tracks number of each item ordered
     60             $_SESSION['cart'][$k] = $_SESSION['cart'][$k] + $v;
     61
     62
     63
     64         }
     65     }
     66 }
     67 // if this is an update operation
     68 // replace quantities in shopping cart with values entered
     69 else if ($_POST['update'])
     70 {
     71     foreach ($_POST['u_qty'] as $k => $v)
     72     {
     73         // if the value is empty, 0 or negative
     74         // don't bother changing the cart
     75         if ($v != "" && $v >= 0)
     76         {
     77             $_SESSION['cart'][$k] = $v;
     78         }
     79     }
     80 }
     81 // if this is a clear operation
     82 // reset the session and the cart
     83 // destroy all session data
     84 else if ($_POST['clear'])
     85 {
     86     $_SESSION = array();
     87     session_destroy();
     88 }
     90 ?>
     91 <html>
     92 <head></head>
     93 <body>
     94
     95 <h2>Catalog</h2>
     96 Please add items from the list below to your shopping cart.
     97
     98 <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
     99 <table border="0" cellspacing="10">
    100 <?php
    101 // print items from the catalog for selection
    102 foreach ($CATALOG as $k => $v)
    103 {
    104     echo "<tr><td colspan=2>";
    105     echo "<b>" . $v['desc'] . "</b>";
    106     echo "</td></tr>\n";
    107     echo "<tr><td>";
    108     echo "Price per unit: " . $CATALOG[$k]['price'];
    109     echo "&nbsp;&nbsp; Quantity: ";
    110     echo "<input size=4 type=text name=\"a_qty[" . $k . "]\">";
    111     echo "</td></tr><tr><td>";
    112     //if the item is a hamburguer y have to show the extra ingredients
    113     if ($k==101)
    114       {
    115        echo " Please select the extra ingredients that you want (FREE!!):</td><td>";
    116        echo "  <input type='checkbox' name='ing[]' value='Onions'> Onions</td><td>";
    117        echo "  <input type='checkbox' name='ing[]' value='Ketchup'> Ketchup</td><td>";
    118        echo "  <input type='checkbox' name='ing[]' value='Pickles'> Pickles</td><td>";
    119        echo "  <input type='checkbox' name='ing[]' value='Mustard'> Mustard</td><td>";
    120        echo "  </tr></td>";
    121       }
    122     //the same if the item is a hamburguer with cheese
    123     elseif($k==102)
    124      {
    125       echo " Please select the extra ingredients that you want (FREE!!):</td><td>";
    126       echo "  <input type='checkbox' name='ing2[]' value='Onions'> Onions</td><td>";
    127       echo "  <input type='checkbox' name='ing2[]' value='Ketchup'> Ketchup</td><td>";
    128       echo "  <input type='checkbox' name='ing2[]' value='Pickles'> Pickles</td><td>";
    129       echo "  <input type='checkbox' name='ing2[]' value='Mustard'> Mustard</td><td>";
    130       echo "  </td></tr>";
    131      }
    132     //the same if the item is a hotdog
    133     elseif ($k==103)
    134      {
    135       echo " Please select the extra ingredients that you want (FREE!!):</td><td>";
    136       echo "  <input type='checkbox' name='ing3[]' value='Onions'> Onions</td><td>";
    137       echo "  <input type='checkbox' name='ing3[]' value='Ketchup'> Ketchup</td><td>";
    138       echo "  <input type='checkbox' name='ing3[]' value='Pickles'> Pickles</td><td>";
    139       echo "  <input type='checkbox' name='ing3[]' value='Mustard'> Mustard</td><td>";
    140       echo "  </td></tr>";
    141      }
    142     echo "</td></tr>";
    143
    144
    145 }
    146 ?>
    147 <tr>
    148 <td colspan="2">
    149 <input type="submit" name="add" value="Add items to cart">
    150 </td>
    151 </tr>
    152 </table>
    153
    154 <hr />
    155 <hr />
    156
    157 <h2>Shopping cart</h2>
    158
    159 <table width="100%" border="0" cellspacing="10">
    160 <?php
    161 // initialize a variable to hold total cost
    162 $total = 0;
    163 // check the shopping cart
    164 // if it contains values (It COULD be empty)
    165 // look up the SKUs in the $CATALOG array
    166 // get the cost and calculate subtotals and totals
    167 if (is_array($_SESSION['cart']))
    168 {
    169     foreach ($_SESSION['cart'] as $k => $v)
    170     {
    171         // only display items that have been selected
    172         // that is, quantities > 0
    173         if ($v > 0)
    174         {
    175             $subtotal = $v * $CATALOG[$k]['price'];
     176             $total += $subtotal;
    177             echo "<tr><td>";
    178             echo "<b>$v unit(s) of " . $CATALOG[$k]['desc'] . "</b>";
    179
    180             /*//normal hamburguer
    181             if ($k==101)
    182              if (is_array($_POST['ing']))
    183               {
    184                echo "&nbsp; with: ";
    185                //foreach to read the elements
    186                foreach ($_POST ['ing'] as $o)
    187                 {
    188                  echo "&nbsp; $o ";
    189                 }
    190               }
    191             //cheese hamburguer
    192             if ($k==102)
    193              if (is_array($_POST['ing2']))
    194                 {
    195                   echo "&nbsp; with: ";
    196                   //foreach to read the elements
    197                  foreach ($_POST ['ing2'] as $o)
    198                    {
    199                     echo "&nbsp; $o ";
    200                    }
    201                 }
    202             //hotdog
    203             if ($k==103)
    204              if (is_array($_POST['ing3']))
    205                {
    206                  echo "&nbsp; with: ";
    207                  //foreach to read the elements
    208                  foreach ($_POST ['ing3'] as $o)
    209                   {
    210                     echo "&nbsp; $o ";
    211                   }
    212                }*/
    213
    214             echo "</td><td>";
    215             echo "New quantity: <input size=4 type=text name=\"u_qty[" . $k . "]\">";
    216             echo "</td></tr>\n";
    217             echo "<tr><td>";
    218             echo "Price per unit: " . $CATALOG[$k]['price'];
     219             echo "</td><td>";
    220             echo "Sub-total: " . sprintf("%0.2f", $subtotal);
    221             echo "</td></tr>\n";
    222         }
    223     }
    224 }
    225 ?>
    226 <tr>
    227 <td><b>Total without taxes</b></td>
    228 <td><b><?=sprintf("%0.2f", $total)?></b></td>
    229 </tr>
    230 <br>
    231 <tr>
    232 <td>Taxes</td>
    233 <? $taxes = $total * 0.055; ?>
    234 <td><?=sprintf("%0.2f", $taxes) ?></td>
    235 </tr>
    236 <br>
    237 <td><b>TOTAL</b></td>
    238 <? $totaldef = $total + $taxes; ?>
    239 <td><b><?=sprintf("%0.2f", $totaldef) ?></b></td>
    240 </tr>
    241 <br>
    242
    243
    244 <tr>
    245 <td><input type="submit" name="update" value="Update Cart"></td>
    246 <td><input type="submit" name="clear" value="Clear Cart"></td>
    247 </tr>
    248 </table>
    249 </form>
    250
    251 </body>
    252 </html>





Gracias x adelantado. Saludos


Título: Re: mas problemas con php
Publicado por: Red Mx en 26 Octubre 2006, 07:45 am
Citar
Hola, sigo con mi carrito, al final lo unico q tengo q hacer es permitir coger los productos de 1 en 1 y poer seleccionar ingredientes. el problema que tengo es que si cojo por ejemplo 2 hamburguesas con disitintos ingredientes me los trata cmo productos iguales y yo quiero q los trate cmo productos distintos y q los liste tb cmo productos distintos.

bueno una pregunta ese code es tuyo o te lo quebraste de por ahi por que de nada te sirve tener algo que no sabes como funciona o si lo sabes


marcame donde cres que esta el error y te ayudo.


Título: Re: mas problemas con php
Publicado por: ^kazike^ en 26 Octubre 2006, 07:49 am
ok, el codigo es de un libro me dan un carrito y tengo q modificarlo.
bien el problema es: yo marco por ejemplo 1 hamburguesa y cebolla y lo añado al carrito.
Eso lo hace bien, pero el problema viene q si yo ahora quiero añadir una hamburguesa con ketchup por ejemplo en el carrito aparecen 2 hamburguesas, y de ingredientes extra solo ketchup, cuando yo lo q tengo q hacer es q salga cmo una lista de ellas, es decir primero la hambuerguesa con cebolla y luego la hamburguesa con ketchup ok¿?


Título: Re: mas problemas con php
Publicado por: Red Mx en 26 Octubre 2006, 07:55 am
pero quitale los nuemeros de las lineas esos los pone el dreamwaver e que en ingredientes lo estas re asignando el ketchup asi que se borra la cebolla y se pone ketchup tienes que guardar el ingrediente en otra variable


Título: Re: mas problemas con php
Publicado por: ^kazike^ en 26 Octubre 2006, 07:59 am
pero como hago eso?
he estado leyendo y tengo q usar variables de sesion.
Yo construyo un string con todos los ingredientes extra y luego ese string lo imprimo a la vez q el producto principal pero cuando añado otro producto solo me recuerda los ultimos extras añadidos, como guardo todo? un array¿? es que toy perdido ahora mismo


Título: Re: mas problemas con php
Publicado por: .Carlos en 26 Octubre 2006, 08:18 am
Si la hamburguesa con catsup y la hamburguesa con cebolla son dos productos diferentes, porque tomarlos como uno solo?
Crea una variable con el nombre del producto(Hamburguesa) y los ingredientes, asi las Hamburguesas con catsup y las Hamburguesas con cebolla van a ser diferentes.


pero quitale los nuemeros de las lineas esos los pone el dreamwaver e que en ingredientes lo estas re asignando el ketchup asi que se borra la cebolla y se pone ketchup tienes que guardar el ingrediente en otra variable
Saldria la misma porque contaria que son 2 hamburguesas y la cebolla y la catsup como ingrediente.


Título: Re: mas problemas con php
Publicado por: ^kazike^ en 26 Octubre 2006, 08:26 am
ya pero, tengo 3 productos, cada uno con 5 posibles combinaciones , esto es 15 variables??
los productos los cojo de un archivo externo y pa seleccionar los ingredientes inclui un form con botones checkbox, porque los ingredientes no varian el precio entos tengo en el archivo los elementos basicos con los precios.


Título: Re: mas problemas con php
Publicado por: дٳŦ٭ en 26 Octubre 2006, 08:28 am
Citar
ya pero, tengo 3 productos, cada uno con 5 posibles combinaciones , esto es 15 variables??

Es ahí donde entra eval() mas un bucle ;)


Título: Re: mas problemas con php
Publicado por: ^kazike^ en 26 Octubre 2006, 08:34 am
buff nose, tambien mire eso pero no entiendo comoaplicarlo a mi problema, esq estoy empezando con php y toy perdidisimo :s


Título: Re: mas problemas con php
Publicado por: .Carlos en 26 Octubre 2006, 08:35 am
ya pero, tengo 3 productos, cada uno con 5 posibles combinaciones , esto es 15 variables??
los productos los cojo de un archivo externo y pa seleccionar los ingredientes inclui un form con botones checkbox, porque los ingredientes no varian el precio entos tengo en el archivo los elementos basicos con los precios.
No, no vas a definir los productos.
Vas a crear los productos en una sola variable dependiendo de lo que el cliente haya escodigo, si escogio una hamburguesa con cebolla y catsup, pues la variable quedaria Hamburguesa+catsup+cebolla(por ejemplo), pero si el cliente escogio la hamburguesa solo con catsup quedaria: Hamburguesa+catsup.

Código:
<?php
// Ejemplo 1
$producto = "Hamburguesa";
$extras = "catsup+cebolla";
$productoTotal = $producto."+".$extras; //Quedaria Hamburguesa+catsup+cebolla

// Ejemplo 2
$producto = "Hamburguesa";
$extras = "catsup";
$productoTotal = $producto."+".$extras; //Quedaria Hamburguesa+catsup
?>

Asi el primer pedido es diferente al segundo y no se puede contar junto con el segundo.


Título: Re: mas problemas con php
Publicado por: дٳŦ٭ en 26 Octubre 2006, 08:37 am
A ver muchacho, revisa la sistaxis, descripción y ejemplos de http://www.php.net/eval ahí mismo está el manual de referencia de php, si te haces muchos lios con las variables te recomiendo que empieces desde cero con ejemplos básicos, ya que los domines te lanzas a jugar con eval, variables de sesión, es fácil, es cuestión de esmero y dedicación.

Practica con los ejemplos de eval() y te darás cuenta.  ;)

Suerte y paciencia.


Título: Re: mas problemas con php
Publicado por: ^kazike^ en 26 Octubre 2006, 08:38 am
vale eso lo entiendo, pero como lo junto con lo que tengo ya hecho? es posible?


Título: Re: mas problemas con php
Publicado por: .Carlos en 26 Octubre 2006, 08:41 am
Pues si se puede, es cuestion de que modifiques el codigo.


Título: Re: mas problemas con php
Publicado por: ^kazike^ en 26 Octubre 2006, 08:45 am
vale, pero como¿?  :huh:
Por ejemplo lo de que los items principales se obtengan de un fichero?
y otra cosa para q al actualizar el carrito no pierda lo anterior no necesitaria variables de sesion?


Título: Re: mas problemas con php
Publicado por: Red Mx en 27 Octubre 2006, 01:24 am
no es por desanimarte hermano pero primero te recomiendo que paredas lo basico de lenguaje C ya que de ahi se basa el php despues estudies el php desde 0

imagina un niño en bicicleta que todavia no sabe caminar


primero lo primero y luego crearas tu web site sin nigun problema por que te estas agogando en un vaso d agua ademas lo que tu quieres en tu trabajo no es precisamente una pagina web de Mcdonal´s o Burguer king