You have a syntax error in the SQL query that you use to insert the data in the table where you put ' $desde'.''$hasta'
. Maybe I should put '$desde', '$hasta'
, but I preferred to show you how to do it correctly.
Using prepared queries means adding a bit more code, but it makes it easier for you to read the code, debug it and avoid SQL injection attacks.
Here is an example of how to do your homework using prepared queries (below I suggest some changes to the JavaScript code):
<?php
require('conexion.php');
$consulta = $mysqli->prepare("
SELECT
SUM(total) * 0.015 suma_total
FROM venta
WHERE
idusuario = ?
AND fecha BETWEEN ? AND ?
");
if ($consulta === false) {
die('Error en la consulta');
}
/* Cargamos los datos y ejecutamos la consulta */
$consulta->bind_param("i", $_POST["idusuario"]);
$consulta->bind_param("s", $_POST["fechadesde"]);
$consulta->bind_param("s", $_POST["fechahasta"]);
if ($consulta->execute() === false) {
die($consulta->error);
}
/* Obtenemos el resultado y obtenemos el primer registro con fetch_assoc */
$resultado = $consulta->get_result();
if ($resultado === false) {
die("Error al obtener el resultado: ". $consulta->errno);
}
$datos = $resultado->fetch_assoc();
if ($datos === false) {
die("¿No hay datos? (!)");
}
$suma = $datos['suma_total'];
/* Preparamos la consulta de introducción de datos */
$consulta = $mysqli->query("
INSERT INTO comision (
idusuario,
fecha_comision,
total_comision,
desde,
hasta
) VALUES (
?,
CURDATE(),
?,
?,
?
)
");
/* Cargamos los datos y ejecutamos la consulta */
$consulta->bind_param("i", $_POST["idusuario"]);
$consulta->bind_param("i", $suma);
$consulta->bind_param("s", $_POST["fechadesde"]);
$consulta->bind_param("s", $_POST["fechahasta"]);
if ($consulta->execute() === false) {
die($consulta->error);
}
echo "registro guardado";
I suggest the following changes to your JavaScript code:
- ALWAYS use the end of judgment indicator
;
.
- If you have already defined a function called
formSubmit
use it as a parameter of ready
and do not create a function to call a function.
- It is better to send data in
json
to PHP than to mount a string that could suffer problems in the interpretation due to badly escaped URL characters.
- In the event
success
sends the content of the variable resp
to the console and not a text string that sets "resp"
.
Here are the modifications:
function formSubmit() {
$('#formComi').submit(function(e) {
e.preventDefault();
$.ajax({
url: 'phps/procesarcomisiones.php',
type: 'post',
data: {
'idusuario': $('#idusuario').val(),
'fechadesde': $('#fechadesde').val(),
'fechahasta': $('#fechahasta').val()
},
beforeSend: function() {
console.log('enviando datos');
},
success: function(resp) {
console.log(resp);
}
});
});
}
$(document).ready(formSubmit);