To show related product, I chose the value by GET method, in this case the value is the id of the product.
It obtained the data through a query, in this case the example is the colors that the product has.
$sql = "SELECT * FROM colors WHERE product_id='$id'";
Now in the shopping cart I want to show a section that indicates you might also be interested in these products.
Suppose in the database named products you have 6 products.
id | producto
------ | ------
1 | Cell
2 | Cell
3 | Cell
4 | Cell
5 | Cell
6 | Cell
And in the shopping cart I add the products with the id 1,3,6
As I show in the section you could also be interested in these products except the products already added to the basket.
I have only tested with a product like the example already mentioned.
In this case, how would it be considered or how would the query be.
To show only the products not added to the shopping cart.
This is my shopping cart card.php
//Carro de la compra
//Si esta definida la ID obtenido por URL
if (isset($_GET['articulo'])) {
$id_tutorial = $_GET['articulo'];//Obtenemos el ID del producto añadido, para poder acer comprobaciones a mostrar otros resultados.
//Si esta definido la sesion carro -> es decir si ay algun articulo comprado
if (isset($_SESSION['carrito'])) {
$arreglo = $_SESSION['carrito'];
$encontro = false;
for ($i=0; $i<count($arreglo); $i++) {
if ($arreglo[$i]['Id'] == $_GET['articulo']) {
$encontro = true;
}
}
if ($encontro == false) {
$titulo = "";
$precio = 0;
$precioUSD = 0;
$icon = "";
$stmt = $c->prepare("SELECT titulo,precio,icon,id_autor FROM products WHERE page=? and status=1");
$stmt->bind_param("i",$_GET['articulo']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($titulo,$precio,$icon,$id_autor);
while ($stmt->fetch()) {
//Sentencia prepare -> autor proyecto
$stmtN = $c->prepare("SELECT autor FROM autor WHERE id_autor=?");
$stmtN->bind_param("i", $id_autor);
$stmtN->execute();
$stmtN->bind_result($autor);
$stmtN->fetch();
$stmtN->close();
$datosnuevos = array('Id' => $_GET['articulo'], 'Titulo' => $titulo, 'Precio' => $precio, 'Icon' => $icon, 'Cantidad' => 1 );
/*
#Si se utiliza array_push() para añadir un solo elemento al array, es mejor utilizar $array[] = ya que de esta forma no existe la sobrecarga de llamar a una función.
*/
//array_push($arreglo, $datosnuevos);
$arreglo[] = $datosnuevos;
$_SESSION['carrito'] = $arreglo;
$data = $_SESSION['carrito'];
$value_carrito = count($data);
$_SESSION['compras'] = $value_carrito;
} $stmt->close();
} else {
$stmt->close();
}
}
} else { //Caso falso añadimos primer articulo al carro
$titulo = "";
$precio = 0;
$precioUSD = 0;
$icon = "";
$stmt = $c->prepare("SELECT titulo,precio,icon,id_autor FROM products WHERE page=? and status=1");
$stmt->bind_param("i",$_GET['articulo']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($titulo,$precio,$icon,$id_autor);
while ($stmt->fetch()) {
//Sentencia prepare -> autor proyecto
$stmtN = $c->prepare("SELECT autor FROM autor WHERE id_autor=?");
$stmtN->bind_param("i", $id_autor);
$stmtN->execute();
$stmtN->bind_result($autor);
$stmtN->fetch();
$stmtN->close();
} $stmt->close();
} else {
$stmt->close();
}
$arreglo[] = array('Id' => $_GET['articulo'], 'Titulo' => $titulo, 'Precio' => $precio, 'Icon' => $icon, 'Cantidad' => 1 );
$_SESSION['carrito'] = $arreglo;
$data = $_SESSION['carrito'];
$value_carrito = count($data);
$_SESSION['compras'] = $value_carrito;
//echo "<script>window.location.reload();</script>";
}
}
Update additional details.
The product table.
id_product Producto Marca subcategoría
------------- ---------------- ---------- ------
1 Mini Parlantes 0 1
2 flash Memory 0 1
The category table.
id cat_name categoría
---- ---------- -----------
1 HP 0
2 accesorios 1
3 Samsung 0
Structure:
<!-- language: lang-none -->
CREATE TABLE IF NOT EXISTS categories (
id int(100) NOT NULL,
cat_name text NOT NULL,
categoria int(5) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
- hp
- Accessories
- Samsung
- Accessories
In the HP category we show all HP brand products including accessories among others.
In the accessories subcategory we only show these products: flash memory, speakers, headphones, etc.
Note: Accessories are shown to the corresponding brand.
Now it is a product that does not belong to accessories, for example, a laptop subcategory instead of value 1 is NULL, this product would only be shown in the main category HP.
In the event that there was another subcategory called lapto, this product would be shown in that subcategory.
Proposal : In a certain section the page is required to list 5 related products (from the same category) to those already added to the cart:
Ejemplo con declaración prepare()
Quiero dejar un ejemplo tambien, aunque ya ha sido valorado y aprobado, no veo a nadie contestar en la forma que se a creado la prejunta, ya que no veo en las respuestas la sentencia
prepare()
, para trabajar de manera más segura y enviar nuestros parametros por separado al servidor.Que problema tenemos para enviar mediante
prepare()
, tenemos que asociar los parametros segun nuestra sentencia creado, en este caso tenemos el problema, que segun la compra tendremos mas parametros o menos parametros, como podemos solucionar esto, os dejo un código funcionado correctamente en mi web :)Este ejemplo dará una ventaja inicial sobre cómo construir la consulta
SELECT
:Supongamos
$_SESSION['carrito']
contiene los productos que ya han sido comprados por el cliente y$_SESSION[ 'compras']
mantiene el recuento del número total de productos adquiridos, la consultaSELECT
para recuperar los productos restantes sería así:You should consider using meta tags. That is, create a new table where you add keywords related to the product in question. Very similar to how blogs do it or right here on stackoverflow.
When you create a product, you assign these keywords to it, which allows you to identify other related products. How you list products and display them can be adjusted based on the popularity of the product (views, sales) or if this is a product that you get paid to promote.
I don't know your model, but you should seriously consider expanding it. The more information you can store, the easier it will be to perform data mining and deliver better information to your users.
If you are left exclusively with a single field (or table) where a product can only belong to a single category, you are limiting the options of products that you could show the user.
I understand that you have few products, but this does not mean that you cannot move forward in a more complex and complete model from now on. This will benefit you in the short term by delivering better information to your users and it will be easier to implement now than in the future when your application-model-not products grows.
Analyze how other companies that do the same are managed. Amazon, Ebay, Mercadolibre, Stackoverflow and more, check any blog. They all use tags to identify their posts.
A simple model would be:
1 Product can have 1:1 Categories or 1:N , depending on what you define by category.
And that product should have N Tags or Keywords.
So let's say you have this product:
Kingston memory 64GB
In category you can have let's say these 2:
And how tags you can add to it:
With this, if someone selects a 32 GB Sandisk USB stick , you can show them the 64 GB one, based on knowing that the 32 GB stick shares the Memory and Pendrive tag with the Kingston stick.
And so you build your model and the way you display it.
You could load the IDs of the products you show in a string to exclude them in a second query with NOT IN.
For example:
You could also simply build the array of related products, and loop through it to check if the related product ID is already inside the cart session, and if it's already "continue"; so that it skips it inside the while
And if you need to display x number of products, by skipping you increment the counter variable.
Proposal:
1.. First way in MySql code, you only group what you don't want to be seen and in a single call, you already have the desired filter
as a result you get All the products Except the matches of 1 and 2
To build this structure for N filter it would be
El proceso anterior describe, el proceso de solo formar una cadena,,,, para agrupar los productos que NO quieres que se vean, por eso se pone esta expresión, id!=1,, combinándola
de esta forma WHERE pro.id!=1.
1..Solo obtienes la lista del carrito.
2..Sacas del carrito los productos seccionados.
3..Realizas un filtro en Mysql de los productos que ya estan en el carrito, mostrando así , los que no están en el carro.
4.. mostrar los productos restantes, o diferentes ala lista ingresada del carrito.
Esto se me ocurre como una manera rápida de excluir los valores (NO te recomiendo usarlo con demasiados valores de ID ya que esto equivale a una fila de puros OR negados).
Esto muestra todos los registros menos los que
product_id
sea 1 , 3 o 6En el siguiente enlace podras descargar un ejemplo de un Carrito de Compras en Php y JavaScript; el script de la base de datos ahi viene adjunto.
https://www.dropbox.com/s/q8qb1iaenj79r4w/ejemplo_carrito.zip?dl=0
¿Como Crear Ordenes?