I am trying to enter budgets into a database but I get an error when I choose between one option and another.
I tried to do it with a array
but it kept everything in the same row and that's not what I'm looking for and I can't figure out how to fix it. I leave the complete code for you to guide me and I thank you in advance.
UPDATED 2
Error 1: The data can't get into the database if I don't choose all the options.
Error 2: When using,
array
enter only the name, email and total data. The other boxes enter the wordarray
.NOTE: The unselected items should be saved with value
0
, something that is not achieved
UPDATED 3
Modifying the PHP script, I manage to insert the total, name, email but then it saves the word Array
in the other boxes.
if(isset($_POST['add'])){
if(!empty($_POST['nombre']) && !empty($_POST['email'])){
$add = $conn->prepare("INSERT INTO presupuesto (nombre, email, total, bsimple, todo, frenos, aros) VALUES (:nombre, :email, :total, :bsimple, :todo, :frenos, :aros)");
$add->bindValue(':nombre', $_POST['nombre']);
$add->bindValue(':email', $_POST['email']);
$add->bindValue(':total', $_POST['total']);
$add->bindValue(':bsimple', $_POST['check_list']);
$add->bindValue(':todo', $_POST['check_list']);
$add->bindValue(':frenos', $_POST['check_list']);
$add->bindValue(':aros', $_POST['check_list']);
$add->execute();
echo '<div class="mb-3 badge badge-success">Presupuesto creado</div>';
} else {
echo '<div class="mb-3 badge badge-danger">Error</div>';
}
}
function actualizarValor(estaChequeado, valor) {
var suma_actual = 0;
var campo_resultado = document.getElementById('txtValor');
valor = parseInt(valor);
try {
if (campo_resultado != null) {
if (isNaN(campo_resultado.value)) {
campo_resultado.value = 0;
}
suma_actual = parseInt(campo_resultado.value);
}
} catch (ex) {
alert('No existe el campo de la suma.');
}
if (estaChequeado == true) {
suma_actual = suma_actual + valor;
$(this).closest("label").css('border', '3px solid black');
} else {
suma_actual = suma_actual - valor;
$(this).closest("label").css('border', '3px solid transparent');
}
campo_resultado.value = suma_actual;
}
.checkeable img {
width: 100px;
border: 5px solid transparent;
}
.checkeable input {
display: none;
}
.checkeable input:checked + img {
border-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Presupuesto</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<h2>Mi Bicicleta</h2>
<div style="padding-top: 1rem;">
<p>Presupuesto</p>
<span style="font-size: 1.4rem;">U$S</span>
<input type="text" name="total" style="font-size: 1.4rem; padding: .4rem; border: none;" readonly id="txtValor" value="0">
</div>
<div class="pt-4">
<label class="checkeable">
<img src="https://cdn2.iconfinder.com/data/icons/ios-7-icons/50/bicycle-512.png"><br>
<input type="checkbox" name="simple" value="60" onclick="actualizarValor(this.checked, this.value);"> Bicicleta Simple $60
</label>
<label class="checkeable ml-3">
<img src="https://cdn2.iconfinder.com/data/icons/ios-7-icons/50/bicycle-512.png"><br>
<input type="checkbox" name="todo" value="86" onclick="actualizarValor(this.checked, this.value);"> Todo Terreno $86
</label>
</div>
<div class="pt-4">
<h4>Como quieres armar tu bicicleta?</h4>
<p>
<input type="checkbox" name="frenoapb" value="180" onclick="actualizarValor(this.checked, this.value);"> Frenos APB - $180
</p>
<p>
<input type="checkbox" name="aros" value="82" onclick="actualizarValor(this.checked, this.value);"> Aros de aluminio - $82
</p>
<p>
<input type="text" name="nombre" > Nombre
</p>
<p>
<input type="text" name="email"> Email
</p>
<button name="add" class="btn btn-primary">Crear Presupuesto</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</body>
</html>
Input checkboxes are sent only if the box is checked, so you need to check that they were actually received in PHP. Easiest is with ternary assignment:
(sentencia booleana) ? valor si la sentencia es cierta : valor si es falsa
It works the same with echo, assign parameters, include as array value, etc.
In the HTML put the names the same as the fields of your table:
I will show you a solution applying what I suggested in several comments.
HTML
We will avoid inline functions , because they are bad practice since they drag Javascript code into the HTML. If tomorrow you have to change something in that function you will have to find all the HTML that have it and modify them.
Here what we will do is listen to the submission of the form, we will collect your data with
serialize
and on the server we will verify what data was sent and what data was not.Another thing you should avoid is the use of
$_SERVER['PHP_SELF']
, as in some contexts it can be a security problem. We won't get into that now, but if you want I'll give you a link to a question I can't remember right now. In its place we are going to put the name of the file that will process the information that you pass to the server, and that must be different from the file that contains the form. Here I have called that fileform-action.php
and assumed that it is in the same directory as the script that contains the form.We have also added a
<div id="result">
to display the result of the Ajax request. This is optional and depends on your context.Well this is the HTML.
javascript
This would be the JS code that would be in the same file as the HTML and that would collect the data and send it to the server via Ajax. You can put this entire block inside the
head
HTML tag above.PHP
Now in PHP we are going to use ternaries to determine what values arrived in the request. Since the checkboxes that were not selected will not travel between the data that is sent, by means of a ternary we can assign the default value that is
0
, as you say in the question, when that data has not been selected.NOTE : This file must be called
form-action.php
or whatever, but it must be the same as what you have written in theaction
form tag.That is all. Try this and if you have any problems let me know in comments.
A solution to your problem is to check
isset()
if the value exists, if not, add a default value, then addinput
a different name to each and create hidden inputs to store the actual values to be processed.You can paste this function in your php code, use it to get your values.
1. Since your table requires
nombre, email, total, bsimple, todo, frenos, aros
I create thoseinput
with thetype=text
.2. Luego para saber el tipo de bicicleta creo un par de inputs con
name=tipo
y detype=radio
esto permite enviar eltipo
y a los input de nombrebsimple
ytodo
agregohidden
para ocultarlos y así estos siempre serán enviados por formulario.3. Cambia los valores según la selección usado el
id
para saber que input cambiar y el eventoonclick
( cuando se da click en la opción visible parabsimple
cambiabsimple
a 65 ytodo
a 0 y viceversa )Por ultimo en tu código PHP recuerda pegar la función de arriba.
CHECKBOX Y RADIO :
Primero debes recordar que los
inputs
de tipo checkbox solo se envían porPOST
oGET
cuando han sido seleccionados, para saber si algo llega por formulario debes usar la funcionisset($_POST["tudato"])
una buena manera de verificar que llego a tu petición es asiendo unecho
del$_POST
.Si tiene esto en tu formulario.
como te das cuenta ninguno de estos esta seleccionado, no tiene
checked
entonces la estructura de$_POST
seria[]
un array vació por lo tantoisset($_POST["foo"])
yisset($_POST["bar"])
seriafalse
para ambos casos, pero si es este otro caso.la estructura de
$_POST
seria[ foo=banana , bar=1 ]
, ya son accesibles yasset[$_POST["foo"]]
yasset[$_POST["foo"]]
daría true.si estas usando los
checkobox
para la lógica de tu formulario, debes complementar con otro elemento de html que son los input de tiporadio
.type="checkbox"
es un input usado para enviar un valor solo si este es seleccionado.type="radio"
es un input usado para enviar solo un valor de varias opciones a seleccionar.