Foros del Web » Programando para Internet » PHP »

:: Como insertar datos en una base de datos MySQL

Estas en el tema de :: Como insertar datos en una base de datos MySQL en el foro de PHP en Foros del Web. Hola a todos. desde un tiempo trato de crear mi propio carrito de compras. he conseguido un par de scripts en php y buen me ...
  #1 (permalink)  
Antiguo 02/05/2004, 13:43
oecarlitoz
Invitado
 
Mensajes: n/a
Puntos:
:: Como insertar datos en una base de datos MySQL

Hola a todos. desde un tiempo trato de crear mi propio carrito de compras.

he conseguido un par de scripts en php y buen me funcionan de maravilla, pero el detalle es que no me pusieron como agregar datos a mis productos por ejemplo:

este archivo se llama carrito.php
Código PHP:
<?php

    
include("db.php");
        
    switch(
$_GET["action"])
    {
        case 
"add_item":
        {
            
AddItem($_GET["id"], $_GET["qty"]);
            
ShowCart();
            break;
        }
        case 
"update_item":
        {
            
UpdateItem($_GET["id"], $_GET["qty"]);
            
ShowCart();
            break;
        }
        case 
"remove_item":
        {
            
RemoveItem($_GET["id"]);
            
ShowCart();
            break;
        }
        default:
        {
            
ShowCart();
        }
    }

    function 
AddItem($itemId$qty)
    {
        
// Will check whether or not this item
        // already exists in the cart table.
        // If it does, the UpdateItem function
        // will be called instead
        
        
global $dbServer$dbUser$dbPass$dbName;

        
// Get a connection to the database
        
$cxn = @ConnectToDb($dbServer$dbUser$dbPass$dbName);
        
        
// Check if this item already exists in the users cart table
        
$result mysql_query("select count(*) from cart where cookieId = '" GetCartId() . "' and itemId = $itemId");
        
$row mysql_fetch_row($result);
        
$numRows $row[0];
        
        if(
$numRows == 0)
        {
            
// This item doesn't exist in the users cart,
            // we will add it with an insert query

            
@mysql_query("insert into cart(cookieId, itemId, qty) values('" GetCartId() . "', $itemId, $qty)");
        }
        else
        {
            
// This item already exists in the users cart,
            // we will update it instead
            
            
UpdateItem($itemId$qty);
        }
    }
    
    function 
UpdateItem($itemId$qty)
    {
        
// Updates the quantity of an item in the users cart.
        // If the qutnaity is zero, then RemoveItem will be
        // called instead

        
global $dbServer$dbUser$dbPass$dbName;

        
// Get a connection to the database
        
$cxn = @ConnectToDb($dbServer$dbUser$dbPass$dbName);
        
        if(
$qty == 0)
        {
            
// Remove the item from the users cart
            
RemoveItem($itemId);
        }
        else
        {
            
mysql_query("update cart set qty = $qty where cookieId = '" GetCartId() . "' and itemId = $itemId");
        }
    }
    
    function 
RemoveItem($itemId)
    {
        
// Uses an SQL delete statement to remove an item from
        // the users cart

        
global $dbServer$dbUser$dbPass$dbName;

        
// Get a connection to the database
        
$cxn = @ConnectToDb($dbServer$dbUser$dbPass$dbName);
        
        
mysql_query("delete from cart where cookieId = '" GetCartId() . "' and itemId = $itemId");
    }
    
    function 
ShowCart()
    {
        
// Gets each item from the cart table and display them in
        // a tabulated format, as well as a final total for the cart
        
        
global $dbServer$dbUser$dbPass$dbName;

        
// Get a connection to the database
        
$cxn = @ConnectToDb($dbServer$dbUser$dbPass$dbName);
        
        
$totalCost 0;
        
$result mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" GetCartId() . "' order by items.itemName asc");
        
?>
        <html>
        <head>
        <title> Your Shopping Cart </title>
        <script language="JavaScript">
        
            function UpdateQty(item)
            {
                itemId = item.name;
                newQty = item.options[item.selectedIndex].text;
                
                document.location.href = 'cart.php?action=update_item&id='+itemId+'&qty='+newQty;
            }
        
        </script>
        </head>
        <body bgcolor="#ffffff">
        
<h1>Mi carrito de compras</h1>
        <form name="frmCart" method="get">
        <table width="100%" cellspacing="0" cellpadding="0" border="0">
            <tr>
                
      <td width="15%" height="25" bgcolor="red"> <font face="verdana" size="1" color="white"> 
        &nbsp;&nbsp;<b>Cantidad</b> </font> </td>
                
      <td width="55%" height="25" bgcolor="red"> <font face="verdana" size="1" color="white"> 
        <b>Producto</b> </font> </td>
                
      <td width="20%" height="25" bgcolor="red"> <font face="verdana" size="1" color="white"> 
        <b>Precio</b> </font> </td>
                
      <td width="10%" height="25" bgcolor="red"> <font face="verdana" size="1" color="white"> 
        <b>Eliminar?</b> </font> </td>
            </tr>
            <?php
            
            
while($row mysql_fetch_array($result))
            {
                
// Increment the total cost of all items
                
$totalCost += ($row["qty"] * $row["itemPrice"]);
                
?>
                    <tr>
                        <td width="15%" height="25">
                            <font face="verdana" size="1" color="black">
                                <select name="<?php echo $row["itemId"]; ?>" onChange="UpdateQty(this)">
                                <?php
                                
                                    
for($i 1$i <= 20$i++)
                                    {
                                        echo 
"<option ";
                                        if(
$row["qty"] == $i)
                                        {
                                            echo 
" SELECTED ";
                                        }
                                        echo 
">" $i "</option>";
                                    }
                                
?>
                                </select>
                            </font>
                        </td>
                        <td width="55%" height="25">
                            <font face="verdana" size="1" color="black">
                                <?php echo $row["itemName"]; ?>
                            </font>
                        </td>
                        <td width="20%" height="25">
                            <font face="verdana" size="1" color="black">
                                $<?php echo number_format($row["itemPrice"], 2"."","); ?>
                            </font>
                        </td>
                        
      <td width="10%" height="25"> <font face="verdana" size="1" color="black"> 
        <a href="cart.php?action=remove_item&id=<?php echo $row["itemId"]; ?>">Elimar</a> 
        </font> </td>
                    </tr>
                <?php
            
}
            
            
// Display the total
            
?>
                    <tr>
                        <td width="100%" colspan="4">
                            <hr size="1" color="red" NOSHADE>
                        </td>
                    </tr>
                    <tr>
                        
      <td width="70%" colspan="2"> <font face="verdana" size="1" color="black"> 
        <a href="products.php">&lt;&lt;Regresar a nuestra lista de productos</a></font></td>
                        <td width="30%" colspan="2">
                            <font face="verdana" size="2" color="black">
                                <b>Total: $<?php echo number_format($totalCost2"."","); ?></b>
                            </font>
                        </td>
                    </tr>
                </table>
                </form>
            </body>
            </html>
            <?php
    
}

?>
y Este se llama productos.php

Código PHP:
<?php

    
// This page will list all of the items
    // from the items table. Each item will have
    // a link to add it to the cart

    
include("db.php");
    
    
// Get a connection to the database
    
$cxn = @ConnectToDb($dbServer$dbUser$dbPass$dbName);
    
$result mysql_query("select * from items order by itemName asc");
    
?>
        <html>
        <head>
        <title> Product List </title>
        </head>
        <body bgcolor="#ffffff">
        
<h1>Productos</h1>
        <table width="100%" cellspacing="0" cellpadding="0" border="0">
            <tr>
                
    <td width="30%" height="25" bgcolor="red"> <font face="verdana" size="1" color="white"> 
      &nbsp;&nbsp;<b>Product</b>o </font> </td>
                
    <td width="10%" height="25" bgcolor="red"> <font face="verdana" size="1" color="white"> 
      <b>Precio</b> </font> </td>
                
    <td width="50%" height="25" bgcolor="red"> <font face="verdana" size="1" color="white"> 
      <b>Descripcion</b></font> </td>
                
    <td width="10%" height="25" bgcolor="red"> <font face="verdana" size="1" color="white"> 
      <b>Agregar</b></font> </td>
            </tr>
            <?php
            
while($row mysql_fetch_array($result))
            {
            
?>
                <tr>
                    <td width="30%" height="25">
                        <font face="verdana" size="1" color="black">
                            <?php echo $row["itemName"]; ?>
                        </font>
                    </td>
                    <td width="10%" height="25">
                        <font face="verdana" size="1" color="black">
                            $<?php echo $row["itemPrice"]; ?>
                        </font>
                    </td>
                    <td width="50%" height="25">
                        <font face="verdana" size="1" color="black">
                            <?php echo $row["itemDesc"]; ?>
                        </font>
                    </td>
                    
    <td width="10%" height="25"> <font face="verdana" size="1" color="black"> 
      <a href="cart.php?action=add_item&id=<?php echo $row["itemId"]; ?>&qty=1">Agregar 
      a carrito</a></font></td>
                </tr>
                <tr>
                    <td width="100%" colspan="4">
                        <hr size="1" color="red" NOSHADE>
                    </td>
                </tr>
            <?php
            
}
        
?>
            <tr>
                
    <td width="100%" colspan="4"> <font face="verdana" size="1" color="black"> 
      <a href="cart.php">Ver Mi carrito de compras</a></font></td>
            </tr>
        </table>
    </body>
</html>
Y lo unico que me dieron para meter datos a la base es este codigo SQL.

insert into items values(0, 'Tony Hawk 3', 'Tony Hawk is back. Join him in this popular skating game where speed, collisions and tricks come together to produce the best skating game of all time!', 23.95);

insert into items values(0, 'FIFA Soccer 2002', 'The FIFA range of soccer games are the most popular in their genre. FIFA Soccer 2002 includes an all new team line up, advanced management capabilities, and richer, more realistic graphics.',36.50);

insert into items values(0, 'SSX Tricky', 'Image snowboarding down a steep hill at 100 miles per hour and you have SSX Tricky. It\'s packed with new players, new moves, and a whole new list of stages to complete.', 45.50);


Lo que quisiera es como puedo hacer un formulario que meta datos a mi base. sin necesidad de entrar al SQL y hacerlo manual..


Si pueden ayudarme seria exelente.

saludos y aqui tambien les dejo las tablas sql.

create database cart;

create table items
(
itemId int auto_increment not null,
itemName varchar(50),
itemDesc varchar(250),
itemPrice decimal(4,2),
primary key(itemId),
unique id(itemId)
);

create table cart
(
cartId int auto_increment not null,
cookieId varchar(50),
itemId int,
qty int,
primary key(cartId),
unique id(cartId)

);

Un saludo
  #2 (permalink)  
Antiguo 02/05/2004, 14:49
 
Fecha de Ingreso: noviembre-2002
Ubicación: Barcelona - España
Mensajes: 270
Antigüedad: 21 años, 5 meses
Puntos: 0
No es que te pongan como agregar registros, leete un poco el manuel para saber como se insertan, es muy fácil, pero tienes que leerte el manual, y si después de leerlo no lo consigues hacer, te lo explicaremos
  #3 (permalink)  
Antiguo 02/05/2004, 14:56
oecarlitoz
Invitado
 
Mensajes: n/a
Puntos:
:: He leido el manual

Hola he leido el manual y esta todo bien, pero en niguna parte indica de como insertar datos a la base de dato..

En fin voy a buscarlos de manera manual voy a ver si puedo hacerlo de todas maneras muchas gracias.

  #4 (permalink)  
Antiguo 02/05/2004, 15:19
 
Fecha de Ingreso: noviembre-2002
Ubicación: Barcelona - España
Mensajes: 270
Antigüedad: 21 años, 5 meses
Puntos: 0
Hola, en el problema del autentificador, abajo tu mismo has puesto para insertar registros a una base de datos INSERT INTO
  #5 (permalink)  
Antiguo 02/05/2004, 15:48
Avatar de Gerald  
Fecha de Ingreso: julio-2003
Mensajes: 1.356
Antigüedad: 20 años, 9 meses
Puntos: 2
Y tu manual

en el script que u haz puesto en tu web se ve insertando datos a la db... es cuestion de logica y leerte el manual de mysql.

http://www.mysl-hispano.org
Tal vez algo de Normalizacion de DB

http://www.starlinux.net/staticpages...20723012237361
__________________
Solo por Hoy: Trataré de fortalecer mi mente. Estudiaré y aprenderé algo útil
Hoteldipity
Arte Caracol
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 05:02.