PHP - PROBLEMA AL RECARGAR LA PÁGINA

 
Vista:
sin imagen de perfil
Val: 14
Ha aumentado su posición en 14 puestos en PHP (en relación al último mes)
Gráfica de PHP

PROBLEMA AL RECARGAR LA PÁGINA

Publicado por Andy (8 intervenciones) el 11/07/2018 20:34:03
Al recargar la página se aumenta también la cantidad del ultimo producto que agregue al carrito


Este es mi codigo;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 
<?php
	include_once('clases/producto.php');
	include_once('clases/carrito.php');
	$product = new Product();
	$cart = new Cart();
	if(isset($_GET['action'])){
		switch ($_GET['action']){
			case 'add':
				$cart->add_item($_GET['code'], $_GET['amount']);
			break;
			case 'remove':
				$cart->remove_item($_GET['code']);
			break;
		}
	}
?>

index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Carrito de compras</title>
	<script type="text/javascript" src="js/functions.js"></script>
 
	<style>
 
html { box-sizing: border-box; }
*, *:before, *:after {
    box-sizing: inherit;
    margin: 0;
    padding: 0;
}
.click {
    background-color: #1abc9c;
    border: none;
    border-radius: 2px;
    display: block;
    color: #fff;
    font-family: 'segoe ui';
    margin: 20px auto;
    padding: 6px 9px;
    transition: background-color .3s ease;
}
.click:hover {
    background-color: #e67e22;
}
.click:focus { outline: none; }
 
/* Modal window */
.modal {
    background-color: #fff;
    box-shadow: 0px 25px 69px rgba(0,0,0,.2),
        0px 10px 25px rgba(0,0,0,.1);
    display: block;
    left: calc((100% - 400px) / 2);
    position: absolute;
    transform: scale(0, 0);
    transition: transform .4s ease;
    top: 60px;
    width: 400px;
}
.modal.visible {
    opacity: 1;
    transform: scale(1, 1);
}
.modal > .head {
    color: #777;
    font-family: 'segoe ui';
    font-size: 20px;
    font-weight: bold;
    padding: 18px 10px;
    text-align: center;
}
.modal > .body {
    background-color: #f9f9f9;
    padding: 24px;
}
.modal > .body > .message {
    color: #777;
    display: block;
    font-family: 'segoe ui';
    font-size: 17px;
    text-align: center;
    width: 100%;
}
.modal > .foot {
    padding: 12px 24px;
    text-align: center;
}
.modal > .foot > button {
    border: none;
    background-color: transparent;
    color: #777;
    cursor: pointer;
    font-family: 'segoe ui';
    font-size: 16px;
    font-weight: 400;
    padding: 8px;
    text-transform: uppercase;
    transition: background-color .3s ease;
}
.modal > .foot > button:hover {
    background-color: #f7f7f7;
}
.modal > .foot > button:focus {
    outline: none;
}
.modal > .foot > button[data-action="OK"] {
    color: #3498db;
}
 
p.text {
    color: #555;
    font-family: 'segoe ui';
    font-size: 22px;
    margin-top: 50px;
    height: 0px;
    opacity: 0;
    text-align: center;
    transition: opacity 1s ease,
        visiblity 1s ease;
    visibility: hidden;
}
p.text.visible {
    height: auto;
    opacity: 1;
    padding: 20px;
    visibility: visible;
}
 
</style>
</head>
<body>
	<div class="content">
		<table border="1px" cellpadding="5px" width="100%">
			<thead class="cartHeader" display="off">
				<tr>
					<th colspan="6">MI CARRITO DE COMPRAS</th>
				</tr>
				<tr>
					<th colspan="3">Total pagar: <?=$cart->get_total_payment();?></th>
					<th colspan="3">Total items: <?=$cart->get_total_items();?></th>
				</tr>
			</thead>
			<tbody class="cartBody">
				<tr>
					<th>Codigo</th>
					<th>Producto</th>
					<th>Precio</th>
					<th>Cantidad</th>
					<th>Subtotal</th>
					<th>Opcion</th>
				</tr>
				<?=$cart->get_items();?>
			</tbody>
		</table>
 
		   <tr>
					<th colspan="6">
 
                    <button class="click">Click me!</button></th>
 
				</tr>
<!-- <tr>
					<th colspan="6">

                    <button class="click" onClick="return confirm("hola");" >Click me!</button></th>

				</tr> -->
		<br><br>
		<table border="1px" cellpadding="5px" width="100%">
			<thead class="productsHeader">
				<tr>
					<th colspan="6">LISTA DE PRODUCTOS</th>
				</tr>
				<tr>
					<th>Codigo</th>
					<th>Producto</th>
					<th>Descripcion</th>
					<th>Precio</th>
					<th>Cantidad</th>
					<th>Opcion</th>
				</tr>
			</thead>
			<tbody class="productsBody">
				<?=$product->get_products();?>
			</tbody>
		</table>
 
	</div>
 
 
<div class="modal">
    <section class="body">
        <span class="message">
            Primero debes registrar los numeros de serie!!
        </span>
    </section>
    <section class="foot">
        <button data-action="NO">Cancelar</button>
        <button data-action="OK">Aceptar</button>
    </section>
</div>
 
<p id="text" class="text"></p>
 
<script type="text/javascript">
 
var btnOpenModal = document.querySelector('.click');
var modalEndWorld = document.querySelector('.modal');
 
btnOpenModal.addEventListener('click', function() {
    modalEndWorld.classList.add('visible');
});
modalEndWorld.addEventListener('click', function(e) {
    var textArea = document.getElementById('text');
    if(e.target.tagName === 'BUTTON') {
        var action = e.target.getAttribute('data-action');
        var content;
        if(action === 'OK') {
            content ='<meta http-equiv="Refresh" content="1; URL=numeros.php" />';;
            textArea.style.color = "#D53400";
        } else {
            content = '<meta http-equiv="Refresh" content="1; URL=" />';
            textArea.style.color = "#27ae60"
        }
        textArea.innerHTML = content;
        modalEndWorld.classList.remove('visible');
        textArea.classList.add('visible');
    }
 
});
 
 
</script>
 
</body>
</html>


producto.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
	include_once('conexion.php');
	class Product extends Model{
		public $code;
		public $product;
		public $description;
		public $price;
 
		public function __construct(){
      parent::__construct();
    }
 
		public function get_products(){
      $sql = $this->db->query("SELECT * FROM tbl_productos");
      $html = '';
      foreach ($sql->fetch_all(MYSQLI_ASSOC) as $key){
        $code = "'".$key['producto_codigo']."'";
        $html .= '<tr>
                    <td>'.$key['producto_codigo'].'</td>
                    <td>'.$key['producto_nombre'].'</td>
                    <td>'.$key['producto_descripcion'].'</td>
                    <td align="right">'.$key['producto_precio'].'</td>
                    <td align="right">
                      <input type="number" id="'.$key['producto_codigo'].'" value="1" min="1">
                    </td>
                    <td>
                      <button onClick="addProduct('.$code.');">
                        Agregar
                      </button>
                    </td>
                  </tr>';
      }
      return $html;
   	}
 
 		public function search_code($code){
 			$sql = $this->db->query("SELECT * FROM tbl_productos WHERE producto_codigo = '$code'");
      $product = $sql->fetch_all(MYSQLI_ASSOC);
      $status = 0;
      foreach ($product as $key){
    		$this->code = $key['producto_codigo'];
    		$this->product = $key['producto_nombre'];
    		$this->description = $key['producto_descripcion'];
    		$this->price = $key['producto_precio'];
    		$status++;
    	}
    	return $status;
 		}
	}
?>

carrito.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
	class Cart extends Product{
	    public $cart = array();
	    public function __construct(){
	    	parent::__construct();
	    	if(isset($_SESSION['cart'])){
	    		$this->cart = $_SESSION['cart'];
	    	}
	    }
 
	    public function add_item($code, $amount){
			$search = $this->search_code($code);
			if($search > 0){
				$code = $this->code;
				$product = $this->product;
				$price = $this->price;
				$item = array(
					'code' => $code,
					'product' => $product,
					'price' => $price,
					'amount' => $amount
				);
				if(!empty($this->cart)){
					foreach ($this->cart as $key){
						if($key['code'] == $code){
							$item['amount'] = $key['amount'] + $item['amount'];
						}
					}
				}
				$item['subtotal'] = $item['price'] * $item['amount'];
				$id = md5($code);
				$_SESSION['cart'][$id] = $item;
				$this->update_cart();
			}
		}
 
		public function remove_item($code){
			$id = md5($code);
			unset($_SESSION['cart'][$id]);
			$this->update_cart();
			return true;
		}
 
	    public function get_items(){
	    	$html = '';
	    	if(!empty($this->cart)){
	    		foreach ($this->cart as $key){
	    			$code = "'".$key['code']."'";
					$html .= '<tr>
								<td>'.$key['code'].'</td>
								<td>'.$key['product'].'</td>
								<td align="right">'.number_format($key['price'], 2).'</td>
								<td align="right">'.$key['amount'].'</td>
								<td align="right">'.number_format($key['subtotal'], 2).'</td>
								<td>
									<button onClick="deleteProduct('.$code.');">
				                    	Eliminar
				                    </button>
								</td>	
							  </tr>

             
							  ';
				}
	    	}
	    	return $html;
	    }
 
	    public function get_total_items(){
	    	$total = 0;
	    	if(!empty($this->cart)){
	    		foreach ($this->cart as $key){
					$total += $key['amount'];
				}
	    	}
	    	return $total;
	    }
 
	    public function get_total_payment(){
	    	$total = 0;
	    	if(!empty($this->cart)){
	    		foreach ($this->cart as $key){
					$total += $key['subtotal'];
				}
	    	}
	    	return number_format($total, 2);
	    }
 
 
		public function update_cart(){
			self::__construct();
		}
	}
?>
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de xve
Val: 3.943
Oro
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

PROBLEMA AL RECARGAR LA PÁGINA

Publicado por xve (6935 intervenciones) el 15/07/2018 12:21:57
Hola Andy, según entiendo, cada vez que se recarga la pagina, se envia nuevamente la información, y por eso se incrementa el producto.

Una buena opción para ello, es una vez se ha añadido el producto por primera vez, se hace una redirección a la misma pagina sin enviar ningun parametro, de esta manera, posteriormente, por mucho que actualicen, no incrementara.

algo así:
1
header("location:pagina.php");

Hay que tener en cuanta, que para hacer esta redirección, no hay que haber enviado nada de contenido al navegador.

Te puede servir?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 14
Ha aumentado su posición en 14 puestos en PHP (en relación al último mes)
Gráfica de PHP

PROBLEMA AL RECARGAR LA PÁGINA

Publicado por Andy (8 intervenciones) el 17/07/2018 23:11:56
Hola xve, gracias, exactamente eso fue lo que use :)) y ya no me actualizo al recargar
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar