How to make an html dropdown work with PHP post? - javascript

I just modified my php file switching from a text box from one of my fields to a dropdown list and it no longer returns the "sexo" field in the output. Can someone tell me why this is? All I did was switch from a text box to a list.
It won't return all of the results it will only return the values from all columns except the sexo column which should be either Masculino or Femenino
The error I'm guessing has to be in the form or in the POST variable for "sexo"
<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
sec_session_start();
if(!isset($_SESSION['username'])) {
header("Location: index.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1" />
<link rel="stylesheet" href="datepicker.css" type="text/css" />
<link rel="stylesheet" href="demo.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="datepicker.js"></script>
<script type="text/javascript" src="ValidarDatos.js"></script>
<title>Consulta niño Coprodeli Intranet</title>
</head>
<body>
<div id="content">
<div id="logo"> <img src="images/logo.jpg" /> </div>
<ul id="menu">
<li>Home</li>
<li>Niños</li>
<li>Padrinos</li>
<li>Centros</li>
<li>Informes</li>
<li>Usuarios</li>
<li>Salir</li>
</ul>
<div id="intro2">
<h1>Intranet Coprodeli</h1>
<p>Apadrinamiento y Programa<br />
de Niños en Alto Riesgo</p>
<div id="login">
</div>
</div>
<div id="right2">
<h4 class="migas">Estás en: Inicio | Consulta de niños</h4>
<br />
<?php
$output = NULL;
if(isset($_POST['submit'])){
// Connect to the database
$mysqli = NEW MySQLi("localhost","root","","coprodeli");
$nino_id = $mysqli->real_escape_string( $_POST['nino_id']);
$nombre = $mysqli->real_escape_string( $_POST['nombre']);
$apellidos = $mysqli->real_escape_string( $_POST['apellidos']);
$sexo = $mysqli->real_escape_string( $_POST['sexo']);
$estado = $mysqli->real_escape_string( $_POST['estado']);
$fecha_de_nacimiento_desde = $mysqli->real_escape_string( $_POST['fecha_de_nacimiento_desde']);
$fecha_de_nacimiento_hasta = $mysqli->real_escape_string( $_POST['fecha_de_nacimiento_hasta']);
$tipo_de_centro = $mysqli->real_escape_string( $_POST['tipo_de_centro']);
$nombre_del_centro = $mysqli->real_escape_string( $_POST['nombre_del_centro']);
$region_del_centro = $mysqli->real_escape_string( $_POST['region_del_centro']);
$nivel_de_estudio = $mysqli->real_escape_string( $_POST['nivel_de_estudio']);
$entrada_desde = $mysqli->real_escape_string( $_POST['entrada_desde']);
$entrada_hasta = $mysqli->real_escape_string( $_POST['entrada_hasta']);
$egreso_desde = $mysqli->real_escape_string( $_POST['egreso_desde']);
$egreso_hasta = $mysqli->real_escape_string( $_POST['egreso_hasta']);
//Query the database
$resultSet = $mysqli->query("SELECT nino_id, nombre, apellidos, sexo, estado, fecha_de_nacimiento_desde, fecha_de_nacimiento_hasta,
tipo_de_centro, nombre_del_centro, region_del_centro, nivel_de_estudio, entrada_desde, entrada_hasta, egreso_desde, egreso_hasta FROM nino
WHERE nino_id = '$nino_id' AND nombre = '$nombre' AND apellidos = '$apellidos' AND sexo = '$sexo' AND estado = '$estado' AND fecha_de_nacimiento_desde = '$fecha_de_nacimiento_desde'
AND fecha_de_nacimiento_hasta = '$fecha_de_nacimiento_hasta' AND tipo_de_centro = '$tipo_de_centro' AND nombre_del_centro = '$nombre_del_centro' AND
region_del_centro = '$region_del_centro' AND nivel_de_estudio = '$nivel_de_estudio' AND entrada_desde = '$entrada_desde' AND entrada_hasta = '$entrada_hasta'
AND egreso_desde = '$egreso_desde' AND egreso_hasta = '$egreso_hasta';" ) ;
// Edited on 9/7/2015 12:39PM by Anthony Sawah. I changed it from " if($resultSet['num_rows'] > 0) { " to " if($resultSet->num_rows > 0) {"
if($resultSet->num_rows > 0) {
while($rows = $resultSet->fetch_assoc())
{
$nino_id = $rows['nino_id'];
$nombre = $rows['nombre'];
$apellidos = $rows['apellidos'];
$sexo = $rows['sexo'];
$estado = $rows['estado'];
$fecha_de_nacimiento_desde = $rows['fecha_de_nacimiento_desde'];
$fecha_de_nacimiento_hasta = $rows['fecha_de_nacimiento_hasta'];
$tipo_de_centro = $rows['tipo_de_centro'];
$nombre_del_centro = $rows['nombre_del_centro'];
$region_del_centro = $rows['region_del_centro'];
$nivel_de_estudio = $rows['nivel_de_estudio'];
$entrada_desde = $rows['entrada_desde'];
$entrada_hasta = $rows['entrada_hasta'];
$egreso_desde = $rows['egreso_desde'];
$egreso_hasta = $rows['egreso_hasta'];
$output .= "<tr><td>".$estado."</td><td>".$nino_id."</td><td>".$apellidos."</td><td>".$nombre."</td><td>".$egreso_desde."</td><td>".$egreso_hasta."</td>";
}
}else{
$output = "No results";
}
}
?>
<fieldset class="required">
<legend>Consulta de niños:</legend>
<form method ="POST">
<p>ID niño: <input type="text" name="nino_id" />
<br> </br>
Nombre: <input type="text" name="nombre" />
<br> </br>
Apellidos: <input type="text" name="apellidos" /> <br> </br>
Sexo:
<select name="sexo">
<option value=""> Select...</option>
<option value="Masculino">Masculino</option>
<option value="Femenino">Femenino</option>
</select>
<br>
</br>
Estado: <input type="text" name="estado" /> <br> </br>
Fecha de
nacimiento desde
(DD-MM-YYYY): <input type="text" name="fecha_de_nacimiento_desde" /> <br> </br>
Fecha de
nacimiento hasta
(DD-MM-YYYY): <input type="text" name="fecha_de_nacimiento_hasta" /> <br> </br>
Tipo de centro: <input type="text" name="tipo_de_centro" /> <br> </br>
Nombre Del Centro: <input type="text" name="nombre_del_centro" /> <br> </br>
Región del Centro: <input type="text" name="region_del_centro" /> <br> </br>
Nivel de estudio: <input type="text" name="nivel_de_estudio" /> <br> </br>
Entrada desde
(DD-MM-YYYY): <input type="text" name="entrada_desde" /> <br> </br>
Entrada hasta
(DD-MM-YYYY): <input type="text" name="entrada_hasta" /> <br> </br>
Egreso desde
(DD-MM-YYYY): <input type="text" name="egreso_desde" /> <br> </br>
Egreso hasta
(DD-MM-YYYY): <input type="text" name="egreso_hasta" /> <br> </br>
<input type="submit" name="submit" value="Search" />
</p>
</form>
</fieldset>
<fieldset id="" class="required">
<legend>Resultado de la búsqueda:</legend>
<form id="form7" name="ResultadoBusqueda" action="ConsultarDetalleNino.php" enctype="multipart/form-data" method="post" >
<table>
<tr>
<td class="especial" width="11"></td>
<td colspan="6" class="especial"> </td>
</tr>
<tr>
<th></th>
<th width="15"></th>
<th width="88">Estado</th>
<th width="104">ID ninos </th>
<th width="234">Apellidos</th>
<th width="81">Nombre</th>
<th width="128">Fecha Ingreso</th>
<th width="106">Fecha Egreso</th>
</tr>
<?php echo $output;?>
</table>
<div class="actions">
<input name="ConsultarDetalleNino" type="submit" class="primaryAction" id="submit-" value="Consultar Detalle">
<input name="Cancelar" type="submit" class="primaryAction" id="submit-" value="Cancelar">
</div>
</form>
<form id="ListadoNinos" name="ListadoNinos" action="InformeNinos.php" method="post" target="_blank"></form>
</fieldset>
<div style="clear: both"></div>
</div>
<div id="footer">
<div id="col1">
<p> <br />
© </p>
</div>
<div id="col2">
<p>Info:<strong></strong><br />
Info2: <strong>completar</strong></p>
</div>
<div id="col3">
<p>
</div>
</div>
</div>
</body>
</html>

The reason being is because $sexo isn't included in your echo'd $output .= variables.
NOTA: There are other variables in your loop that are not part of the echo'd output, so make sure to add those if you want them to be echo'd also.

Related

Disable form button and field with Javascript

I need to disable some filed and button in a form. The form shows user data and the button "Modifica" allow the user to modify field (username, mail, password). If user is worker can modify also exp and photo field. If user is manager this field are hidden.
I wrote some javascript in order to hide and disable fields but the button "modifica" seems to be blocked and I don't know why.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" type="text/css" media="all" href="../CSS/style.css" th:href="#{.../CSS/style.css}"/>
<script type="text/javascript" src="../js/updateProfile.js" th:src="#{/js/updateProfile.js}" defer> </script>
<script type="text/javascript" th:src="#{/js/loadimage.js}" defer ></script> <!--defer fa eseguire js dopo il parsing di html-->
</head>
<body>
<div class="container">
<div th:replace="header :: header"></div>
<h1>Profilo Utente</h1>
<div class="form">
<form action="updateprofile" method="post" enctype="multipart/form-data">
<p>
<label for="username">Username: </label><br>
<input type="text" id="username" name="username" th:attr="value=${session.user.username}" required/><br>
</p>
<p>
<label for="email">Mail: </label><br>
<input type="email" id="email" name="email" th:attr="value=${session.user.email}" required/><br>
</p>
<p>
<label for="password">Password: </label><br>
<input type="password" id="password" name="password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Deve contenere almeno 8 caratteri di cui un numero, una lettera maiuscola e una lettera minuscola." /><br>
</p>
<div id="password-confirm-block">
<p>
<label id="text-password-confirm" for="password-confirm">Reinserisci password: </label><br>
<input type="password" id="password-confirm" />
</p>
<p id="password-message" class="error-message"></p>
</div>
<p>
Tipo di utente:<br>
<input type="radio" name="usertype" id="manager" value="manager" th:checked="${session.user.isManager!=null && session.user.isManager}" required/>
<label for="manager">Manager</label><br>
<input type="radio" name="usertype" id="worker" value="worker" th:checked="${session.user.isManager!= null && !session.user.isManager}" checked required/>
<label for="worker">Worker</label><br>
</p>
<div id="worker-data">
<p>
<label for="exp">Exp level:</label><br>
<select name="exp" id="exp">
<option value="" disabled selected>Exp level</option>
<option value="LOW" th:selected="${session.user.exp == 'LOW'}">LOW</option>
<option value="MEDIUM" th:selected="${session.user.exp == 'MEDIUM'}">MEDIUM</option>
<option value="HIGH" th:selected="${session.user.exp == 'HIGH'}">HIGH</option>
</select><br>
</p>
<p>
<label for="photo">Profile photo</label><br>
<div id="container"style="position: relative; width:300px;">
<canvas id="canvas_background" width="300px" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
</div>
<input type="file" name="photo" id="photo" accept="image/*"/><br>
</div>
<!-- TODO: Rivedere i messaggi di errore inseriti -->
<span class="error-message" th:if="${session.signupfailed}">Salvataggio non riuscito</span>
<p>
<input id="buttonModifica" type="button" value="Modifica" />
<input id="buttonAnnulla" type="reset" value="Annulla" />
<input id="buttonAggiorna" type="submit" value="Aggiorna" />
</p>
</form>
</div>
</div>
</body>
</html>
Javascript:
var username = document.getElementById("username");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordConfirmBlock = document.getElementById("password-confirm-block");
var radioWorker = document.getElementById("worker");
var radioManager = document.getElementById("manager");
var exp = document.getElementById("exp");
var photo = document.getElementById("photo");
var buttonModifica = document.getElementById("buttonModifica");
var buttonAnnulla = document.getElementById("buttonAnnulla");
var buttonAggiorna = document.getElementById("buttonAggiorna");
function init() {
view();
buttonModifica.addEventListener("click", modify, true);
buttonAnnulla.addEventListener("click", view, true);
}
init();
function modify() {
unlockImputs();
buttonAnnulla.hidden=false;
buttonAggiorna.hidden=false;
buttonModifica.hidden=true;
}
function view() {
lockImputs();
buttonAnnulla.hidden=true;
buttonAggiorna.hidden=true;
buttonModifica.hidden=false;
}
function lockImputs (){
username.readOnly=true;
email.readOnly=true;
password.readOnly=true;
passwordConfirmBlock.hidden=true;
radioManager.disabled=true;
radioWorker.disabled=true;
exp.disabled=true;
photo.disabled=true;
}
function unlockImputs (){
username.readOnly=false;
email.readOnly=false;
password.readOnly=false;
radioManager.disabled=false;
radioWorker.disabled=false;
exp.disabled=false;
photo.disabled=false;
}
If you need to disable the button "Modifica", You can just set "disabled" to true for this button's id:
document.getElementById("buttonModifica").disabled = true;
You can get that HTML_DOM with document object then you can apply event listener on it.
Then get another id to which you want to disable and apply disable property into it
For reference :
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/disabled

How to save Dynamically Generated table rows to database

This is My HTML Code
<form method="POST" action="backend/backup.php">
<div class="box-body col-sm-12">
<input type="hidden" name="txtSlNo" id="txtSlNo" value="1">
<div class="col-sm-2">
<label for="Date" class="control-label">Date:</label>
<input type="text" class="text-right" name="date[]" id="date"
value="<?php echo date(" Y/M/D ")?>">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Amount:</label>
<input type="text" size="7" class="text-right" name="txtAmount[]"
id="txtAmount" oninput="calculate()" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Unit:</label>
<input type="text" size="7" name="txtUnit[]" class="text-right"
id="txtUnit" oninput="calculate()" value="1" onkeypress="return
isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Total:</label>
<input type="text" size="7" name="txtTotal[]" class="text-right"
id="txtTotal" oninput="calculate();" oninput="addTotal();" readonly>
</div>
<div class="col-sm-2">
<br>
<!-- <button name="add" id="add" class="btn btn-primary"
hidden="hidden">Add</button> -->
</div>
<div class="col-sm-2">
<input type="button" value="add" name="tableAdd" id="tableAdd"
class="btn btn-primary add add1">
</div>
</div>
<div class="col-xs-12">
<table id="tabledata" name="tabledata">
<thead>
<tr>
<th style="width: 50px; text-align: center !important;"
id="select">select</th>
<th style="width: 50px; text-align: center
!important;">Sl.No</th>
<th style="width: 125px; text-align: center
!important;">Date</th>
<th style="width: 175px; text-align: center
!important;">Service</th>
<th style="width: 80px; text-align: center
!important;">Charge</th>
<th style="width: 80px;">Amount</th>
<th style="width: 80px;">Unit</th>
<th style="width: 80px;">Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button type="button" id="delete-row" class="delete-row">Delete Row</button>
<button class="print" onclick="myFunction()">Print this page</button>
<br>
<label class="GrandTotalLabel" id="GrandTotalLabel">GRAND TOTAL</label>
<input type="text" name="txtGrandTotal" value="00.00" class="txtGrandTotal"
oninput="addTotal();" id="txtGrandTotal" readonly/>
</form>
This is My PHP code
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"]))
{
$numberOfRows = count($_POST['date']); // get the number of rows
for ($i = 0; $i < $numberOfRows; $i++) {
$date = $_POST["date"][$i];
$amount = $_POST["txtAmount"][$i];
$unit = $_POST["txtUnit"][$i];
$total = $_POST["txtTotal"][$i];
$sql = "INSERT INTO backup_master (backup_date, backup_amount,
backup_unit, backup_total) VALUES ('$date', '$amount', '$unit', '$total')";
$result = mysqli_query($conn, $sql);
}
}
?>
This is MY JAVASCRIPT CODE
<script type="text/javascript">
var lclCount=0;
$("#tableAdd").click(function(){
var sl_no = ($('#tabledata tr').length) - 1;
lclCount++;
sl_no++;
var date = $("#date").val();
var amount = $("#txtAmount").val();
var unit = $("#txtUnit").val();
var total = $("#txtTotal").val();
var markup = "<tr><td><input type='checkbox'
name='record' id='"+ lclCount +"'></td><td name='slno' class='slno' id
='slno-"+sl_no+"'>"
+ sl_no + "</td><td>"
+ date + "</td><td>"
+ amount + "</td><td>"
+ unit + "</td><td>"
+ parseFloat(total).toFixed(2) + "</td></tr>";
$("#tabledata").append(markup);
addTotal();
refreshAdd();
});
Here I want to save whatever is generated from dynamically created table data to the database. I tried a lot but unable to do so. Am getting an error saying undefined index date amount etc. Here I want to generate id for every automatically generated table row but unable to figure out how to do so.
Is there any other solution for this ?
Thank in Advance.
Okay....
In my code I'm created a div with class data in which I put four inputs date,amount,unit and total.
I add plus and minus buttons in last for add/remove row.
by clicking plus button clone of previous row appear in last
On submit data of all input will be send to the submit URL.
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"])){
$value = '';
for ($i=0;$i<count($_POST['date']);$i++) {
$value .= '("'.$_POST["date"][$i].'","'.$_POST["amount"][$i].'","'.$_POST["unit"][$i].'","'.$_POST["total"][$i].'"),';
}
$value = rtrim($value,",");
$sql = "INSERT INTO backup_master (backup_date, backup_amount, backup_unit, backup_total) VALUES ".$value;
$result = mysqli_query($conn, $sql);
}
echo '
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body><br />
<div class="container">
<h2>Vertical (basic) form</h2>
<form action="/action_page.php">
<div class="row data" divid="1">
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Date</span>
<input type="text" class="form-control date" value="'.date('Y/M/d').'" id="date-1" placeholder="Enter date" name="date[0]" />
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Amount</span>
<input type="text" class="form-control amount" data-id="1" value="0" id="amount-1" placeholder="Enter Amount" name="amount[0]" />
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Unit</span>
<input type="text" class="form-control unit" data-id="1" id="unit-1" value="0" placeholder="Enter Unit" name="unit[0]" />
</div>
</div>
<div class="col-md-2">
<div class="input-group">
<span class="input-group-addon">Total</span>
<input type="text" class="form-control total" id="total-1" readonly="readonly" name="total[0]" />
</div>
</div>
<div class="col-md-1">
<button class="btn btn-success btn-block plus" type="button" id="p-1">+</button>
<button class="btn btn-danger btn-block minus hide" type="button" id="m-1">-</button>
</div>
</div>
<div class="row"><div class="col-md-3"> </div></div>
<div class="row">
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Grand Total</span>
<input type="text" class="form-control" value="0" id="g-total" readonly="readonly" name="g_total" />
</div>
</div>
<div class="col-md-3">
<button type="submit" class="btn btn-default" name="save">Submit</button>
</div>
</div>
</form>
</div>
</body>
</html>';
?>
<script type="text/javascript">
$(document).on('change','.unit,.amount',function(e) {
id = parseInt($(this).attr("id").replace("unit-", "").replace("amount-",""));
get_total(id);
});
function get_total(id){
unit_d = parseInt($('#unit-'+id).val());
amount = parseInt($('#amount-'+id).val());
total = Math.ceil(amount*unit_d);
$('#total-'+id).val(total);
var g_total = 0;
jQuery('.total').each(function(){
g_total = g_total+parseInt($(this).val());
});
$('#g-total').val(g_total);
}
/****************************JS for add new row****************************/
$(document).on('click','.plus',function(e) {
var thisRow = $('.data').last(".data");
var newid = parseInt(thisRow.attr('divid'))+1;
var cid = parseInt(thisRow.attr('divid'));
var date = $('#date-'+cid).val();
var amount = $('#amount-'+cid).val();
var n_unit = $('#unit-'+cid).val();
var total = $('#total-'+cid).val();
if(date=="") $('#date-'+cid).addClass('error'); else $('#date-'+cid).removeClass('error');
if(amount=="") $('#amount-'+cid).addClass('error'); else $('#amount-'+cid).removeClass('error');
if(n_unit=="") $('#unit-'+cid).addClass('error'); else $('#unit-'+cid).removeClass('error');
if(total=="") $('#total-'+cid).addClass('error'); else $('#total-'+cid).removeClass('error');
if((date!="")&&(amount!="")&&(n_unit!="")&&(total!="")){
$('#date-'+cid+',#amount-'+cid+',#unit-'+cid).attr('readonly','readonly');
newRow = thisRow.clone(true).insertAfter(thisRow).find('input').val('').end().
find('.date').each(function(){
$(this).attr('id', 'date-'+newid);
$(this).attr('name','date['+(newid-1)+']');
$(this).val($('#date-'+cid).val());
$(this).removeAttr('readonly');
}).end().find('.amount').each(function(){
$(this).attr('id', 'amount-'+newid);
$(this).attr('name','amount['+(newid-1)+']');
$(this).attr('data-id',newid);
$(this).val(0);
$(this).removeAttr('readonly');
}).end().find('.unit').each(function(){
$(this).attr('id', 'unit-'+newid);
$(this).attr('name','unit['+(newid-1)+']');
$(this).attr('data-id',newid);
$(this).val(0);
$(this).removeAttr('readonly');
}).end().find('.total').each(function(){
$(this).attr('id', 'total-'+newid);
$(this).attr('name','total['+(newid-1)+']');
$(this).val(0);
}).end().find('.plus').each(function(){
$(this).attr('id', 'p-'+newid);
$(this).attr('data-id', newid);
}).end().find('.minus').each(function(){
$(this).attr('id', 'm-'+newid);
}).end();
thisRow.next('.data').attr("divid",newid).addClass('child');
$('.minus').removeClass('hide');
$('.plus').addClass('hide');
$('#m-'+newid).addClass('hide');
$('#p-'+newid).removeClass('hide');
}
});
/****************************JS for add new row****************************/
/****************************JS for delete row****************************/
$('.minus').click(function(e) {
$(this).closest('.data').remove();
});
/****************************JS for delete row****************************/ </script>

Input form and changing form PHP MySQL

I have made a database and a php to insert new information to the database. When I add some new information, everything works well, but when I want to change these information and update these, my input form look really different. This is my code for adding new information
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8">
<title>Klanten invoeren</title>
</head>
<body>
<form action="SEDDopslaan.php" method="post">
<p>
Reisnummer: <br>
<input name="reisnummer" type="text" size="30" tabindex="1">
</p>
<p>
Land: <br>
<select name="land">
<option value="Nederland">Nederland
<Option value="Duitsland">Duitsland
<Option value="Frankrijk">Frankrijk
<Option value="Belgie">Belgie
</select>
</p>
<p>
Plaats: <br>
<input name="plaats" type="text" size="30" tabindex="3">
</p>
<p>
Vertrekdatum: <br>
<input name="vertrekdatum" type="date" size="30" tabindex="4">
</p>
<p>
Retourdatum: <br>
<input name="retourdatum" type="date" size="30" tabindex="5">
</p>
<p>
Aantalpersonen: <br>
<input name="aantalpersonen" type="text" size="30" tabindex="2">
</p>
<p>
Prijs: <br>
<input name="prijs" type="text" size="30" tabindex="2">
</p>
<p>
Betaling voltooid: <br>
<input name="betalingvoltooid" type="checkbox" value="Ja" size="30" tabindex="2">Ja
<input name="betalingvoltooid" type="checkbox" value="Nee" size="30" tabindex="2">Nee
</p>
<p>
<input type="submit" name="submit" value="Verstuur" title="Verstuur dit formulier" tabindex="6">
</p>
</form>
</body>
</html>
And this is my code for changing information
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8">
<title>Klant wijzigen</title>
</head>
<body>
<?php
// Maken van verbinding
try {
$db = new PDO('mysql:host=localhost;dbname=Reisbureau','root','');
}
catch(PDOException $e) {
echo $e->getMessage();
}
// De SQL opdracht
// Hier wordt de klant geselecteerd om de gegevens op
// te halen die je wilt wijzigen. Het klantnummer zit
// in $_POST[verstopt]
$sql = "SELECT * FROM boeking WHERE reisnummer = $_POST[verstopt]";
$resultaat = $db->query($sql);
// De klantgegevens worden in variabelen gestopt zodat
// we ze in het formulier kunnen zien
foreach($resultaat as $row) {
$reisnummer = $row['reisnummer'];
$land = $row['land'];
$plaats = $row['plaats'];
$vertrekdatum = $row['vertrekdatum'];
$retourdatum = $row['retourdatum'];
$aantalpersonen = $row['aantalpersonen'];
$prijs = $row['prijs'];
$betalingvoltooid = $row['betalingvoltooid'];
}
// Sluiten van verbinding
$db = NULL;
echo "<form action='SEDDwijzigdefinitief.php'method='post'>
<p>Reisnummer: <br>
<input name='reisnummer' type='text' size='30'value=$reisnummer tabindex='1'>
</p>
<p>Land: <br>
<input name='land' type='text' size='30' value=$land tabindex='2'>
</p>
<p>Plaats: <br>
<input name='plaats' type='text' size='30' value=$plaats tabindex='3'>
</p>
<p>vertrekdatum: <br>
<input name='vertrekdatum' type='date' size='30'value=$vertrekdatum tabindex='4'>
</p>
<p>Retourdatum: <br>
<input name='retourdatum' type='date' size='30'value=$retourdatum tabindex='5'>
</p>
<p>Aantalpersonen: <br>
<input name='aantalpersonen' type='text' size='30'value=$aantalpersonen tabindex='5'>
</p>
<p>Prijs: <br>
<input name='prijs' type='text' size='30'value=$prijs tabindex='5'>
</p>
<p>Betalingvoltooid: <br>
<input name='betalingvoltooid' type='text' size='30'value=$betalingvoltooid tabindex='5'>
</p>
<p><input type='submit' name='submit'value='Verstuur' title='Verstuur dit formulier' tabindex='6'>
</p>
</form>"
?>
</body>
</html>
I would like to have exactly the same form in "Add information" as in "Change information"
Your code echo's your variables! You need to write like this:
echo "<input name='prijs' type='text' size='30'value='" . $prijs ."' tabindex='5'>";
So your code will echo the data from your database and not the $prijs plain as a string!
Hope this will help <3
Bonus:
If your $_POST[verstopt] should be a string then use single quotes '' in your query!
To pretend MySQL Injection, you could write your query like this:
$verstopt = mysqli_real_escape_string($db, $_POST[verstopt]);
$sql = "SELECT * FROM boeking WHERE reisnummer = $verstopt";
Change Checkbox value
You could use Javascript to change the value and then you post trough your <form> the input wehre the value is written in. Change the style from your input to style='display:none;' so that the user only can see the checkbox and not the input one which is gonna be used to send to your mysql query.
function test(){
var Result = document.getElementById("checkbox").checked;
document.getElementById('ResultCheckbox').value = Result;
}
<input type="checkbox" id="checkbox" onclick="test();">
<input name="checkboxAnswer" id="ResultCheckbox" value="no">
Have you tried using delevoper tools of your browser to watch the HTML code?
Also, have you tried using quotes to enter your PHP variables?
Something like:
<input name='reisnummer' type='text' size='30' value='".$reisnummer."' tabindex='1'>
What do you mean with form looking "different"?

Who search a variable name with DOM?

I have this code and I need know how to use "nombre" variable to find data with DOM, this aplication works without Jquery.
window.onload = function(e){
<%if(!faltanCampos.equals("")){%>alert("<%=faltanCampos%>")<%}%>
//Ocultamos los vacios'
var j, nombre
i=<%=totalSig%>
for (j=i-1;j > 0;j--){
//nombre="txtsssiidenti" & j'
nombre="txtissicodtui" + j
if (document.frmDatos.nombre.value==""){
menos();
}
}
actualizaNivel();
}
Im translating the aplication from vb to js, the vb code:
Sub window_onload
<%if(!faltanCampos.equals("")){%>msgbox("<%=faltanCampos%>")<%}%>
'Ocultamos los vacios'
Dim j, nombre
i=<%=totalSig%>
for j=i-1 to 0 step -1
'nombre="txtsssiidenti" & j'
nombre="txtissicodtui" & j
if (document.all(nombre).value="") then
menos()
end if
next
actualizaNivel
End sub
FireBug error:
TypeError: document.frmDatos.nombre is undefined
HTML:
<title><%=GestorIdioma.getCadena("ARGES")%> - <%=GestorIdioma.getCadena("DESCRIARCHIVO")%></title>
</head>
<body onmouseover="defaultStatus='<%=GestorIdioma.getCadena("PIEPAGINA")%>'; return true;" >
<iframe name="frameResultado" id="frameResultado" width="0" height="0" src=""></iframe>
<!-- Menu -->
<%# include file="../includeJSP/body_sitemap.inc" %>
<%# include file="../includeJSP/camino.inc" %>
<%if(!Utilidades.dameElemHashtable(h,"EXPURGO").equals("S") && !Utilidades.dameElemHashtable(h,"TRANSFERENCIA").equals("S")){%>
<!-- Opciones auxiliares -->
<%# include file="../includeJSP/OpcionesMant.inc" %>
<%}%>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="175" valign="top">
<form name="frmDatos" method="post" action="">
<!-- Los siguientes campos, aunque no aparecen en esta pestaña, los almacenamos aquí (ya que se heredan) -->
<input type="hidden" name="apartado" value="<%=apartado%>"/>
<input type="hidden" name="hacer" value="<%=hacer%>"/>
<input type="hidden" name="acceso" value="<%=acceso%>"/>
<input type="hidden" name="totalSig" value="<%=totalSig%>"/>
<input type="hidden" name="destino" value="signatura"/>
<input type="hidden" name="txtpsarcodarc" value="<%=Utilidades.dameElemHashtable(hotros,"txtpsarcodarc")%>"/>
<input type="hidden" name="txtpsarcodarcold" value="<%=Utilidades.dameElemHashtable(hotros,"txtpsarcodarcold")%>"/>
<input type="hidden" name="txtisarcodpro" value="<%=Utilidades.dameElemHashtable(hotros,"txtisarcodpro")%>"/>
<input type="hidden" name="masCodNivelA" value="<%=Utilidades.dameElemHashtable(h,"masCodNivelA")%>"/>
<input type="hidden" name="nivelArchivoAnterior" value="<%=Utilidades.dameElemHashtable(h,"masCodNivelA")%>"/>
<!-- Navegación Lateral -->
<%# include file="../includeJSP/NavegaArea.inc" %>
</td>
<td valign="top">
<p class="filareas">
<span class="cmpeti"><%=GestorIdioma.getCadena("SIGNATURA")%></span>
</p>
<div class="grisclaro">
<p class="filacmp">
<span class="inpuazul"><%= GestorIdioma.getCadena("TITULO")%>: </span>
<span class="cmpeti"><%=Utilidades.dameElemHashtable(hotros,"txtssartitulo",session.getAttribute("s54b.varidioma").toString())%></span>
</p>
<%if(Utilidades.dameElemHashtable(h,"TRANSFERENCIA").equals("S")){%>
<div class="grisclaro">
<p class="filacmp">
<span class="cmpeti"><%=GestorIdioma.getCadena("ENTRANSFERENCIA")%></span>
</p>
</div>
<%}
if(Utilidades.dameElemHashtable(h,"EXPURGO").equals("S")){%>
<div class="grisclaro">
<p class="filacmp">
<span class="cmpeti"><%=GestorIdioma.getCadena("ENEXPURGO")%></span>
</p>
</div>
<%}%>
<table border="0" width="100%" cellpadding="0" cellspacing="0">
<tr id="trnivelArchivo">
<td valign="top" colspan="2">
<p class="filacmp">
<span class="inpuazul"><%=GestorIdioma.getCadena("NIVELARCHIVO")%>:</span>
<select name="cboNivelA" class="inpuedi" onchange="javascrip:actualizaNivel()" <%=habilitado%> >
<% boolean carga=false;
anterior=(!Utilidades.dameElemHashtable(h,"masCodNivelA").equals("")?Utilidades.dameElemHashtable(h,"masCodNivelA").toString():"");
if(lnivelAr!=null){
for(i=0;i<lnivelAr.size();i++){
carga=false;
hvalores = (Hashtable)lnivelAr.get(i);
//Comprobamos permisos
if(hvalores.get("RECODRAR").equals("10") && per.damePermiso("MARO",request,response)){
carga=true;
}else if(hvalores.get("RECODRAR").equals("20") && per.damePermiso("MARD",request,response)){
carga=true;
}else if(hvalores.get("RECODRAR").equals("30") && per.damePermiso("MARG",request,response)){
carga=true;
}else if(hvalores.get("RECODRAR").equals("40") && per.damePermiso("MARH",request,response)){
carga=true;
}else if(hvalores.get("RECODRAR").equals("25") && per.damePermiso("MARC",request,response)){
carga=true;
}
if(carga){
if(hvalores.get("RECODRAR").equals(anterior)){
%>
<option class="inpuedi" value="<%=hvalores.get("RECODRAR")%>" selected="selected"><%=hvalores.get("REDESCRI")%></option>
<% }else{%>
<option class="inpuedi" value="<%=hvalores.get("RECODRAR")%>"><%=hvalores.get("REDESCRI")%></option>
<% }
}
}
}else{%>
<option class="inpuedi" value="" selected> </option>
<% }%>
</select>
</p>
</td></tr>
<%
String letras = "";
int numero = 0;
if(lclavesUI!=null){
for(i=0;i<lclavesUI.size();i++){
hvalores= new Hashtable();
hvalores = (Hashtable)lclavesUI.get(i);
letras = Utilidades.dameElemHashtable(hvalores,"letras");
numero = Utilidades.esNumero(Utilidades.dameElemHashtable(hvalores,"numero"))?Integer.parseInt(Utilidades.dameElemHashtable(hvalores,"numero")):0;
}
}
for(j=0;j<Integer.parseInt(totalSig);j++){
//Si no hay SIIDENTI, ponemos una por defecto
if(Utilidades.dameElemHashtable(h,"txtsssiidenti" + j).equals("")) {
numero++;
h.put("txtsssiidenti" + j,Utilidades.formateaNumCaja(letras,numero,true));
}
%>
<tr id="tipoUI<%=j%>"><td valign="top">
<hr/>
<input type="hidden" name="masUIvalida<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"masUIvalida" + j).equals("")?"S":Utilidades.dameElemHashtable(h,"masUIvalida" + j)%>"/>
<input type="hidden" name="masUIdeposito<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"masUIdeposito" + j)%>"/>
<input type="hidden" name="txtissicodtui<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"txtissicodtui" + j)%>"/>
<input type="hidden" name="masUnDescri<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"masUnDescri" + j)%>"/>
<input type="hidden" name="masUnMetros<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"masUnMetros" + j)%>"/>
<p class="filacmp">
<span class="cmpeti"><%=GestorIdioma.getCadena("TIPOUI")%>:</span>
<select name="cboTipoUI<%=j%>" class="inpuedi" onchange="javascript:actualizaTipo('<%=j%>')" <%=habilitado%> >
<option class="inpuedi" value="" selected="selected"> </option>
<%anterior=Utilidades.dameElemHashtable(h,"txtissicodtui" + j);
if(ltipoui!=null){
for(i=0;i<ltipoui.size();i++){
hvalores = (Hashtable)ltipoui.get(i);
if(hvalores.get("UNCODTUI").equals(anterior)){
%>
<option class="inpuedi" value="<%=hvalores.get("UNCODTUI")%>~<%=Utilidades.dameElemHashtable(hvalores,"UNMETROS")%>" selected="selected"><%=hvalores.get("UNDESCRI")%> - <%if ((Utilidades.dameElemHashtable(hvalores,"UNMETROS").substring(0,1)).equals(".")) {%>0<%=Utilidades.dameElemHashtable(hvalores,"UNMETROS").replace('.',',')%><%}else{%><%=Utilidades.dameElemHashtable(hvalores,"UNMETROS").replace('.',',')%><%}%> m.</option>
<% }else{%>
<option class="inpuedi" value="<%=hvalores.get("UNCODTUI")%>~<%=Utilidades.dameElemHashtable(hvalores,"UNMETROS")%>"><%=hvalores.get("UNDESCRI")%> - <%if ((Utilidades.dameElemHashtable(hvalores,"UNMETROS").substring(0,1)).equals(".")) {%>0<%=Utilidades.dameElemHashtable(hvalores,"UNMETROS").replace('.',',')%><%}else{%><%=Utilidades.dameElemHashtable(hvalores,"UNMETROS").replace('.',',')%><%}%> m.</option>
<% }
}
}else{%>
<option class="inpuedi" value="" selected="selected"> </option>
<% }%>
</select>
- <span class="cmpeti"><%=GestorIdioma.getCadena("IDENCAJA")%>:</span>
<input type="text" class="inpuedi" name="txtsssiidenti<%=j%>" size="30" value="<%=Utilidades.formateaNumCaja(Utilidades.dameElemHashtable(h,"txtsssiidenti" + j),0,true, "mostrar")%>" maxlength="15" onblur="javascript:formateaUI(this,'<%=GestorIdioma.getCadena("FORMATOUI")%>');" <%=soloLectura%>/>
</p>
</td>
<td valign="top" align="right">
<hr/>
<p class="filacmp">
<%if(!Utilidades.dameElemHashtable(h,"EXPURGO").equals("S") && !Utilidades.dameElemHashtable(h,"TRANSFERENCIA").equals("S")){%>
<input type="button" name="btnBorrar" class="boton" value="<%=GestorIdioma.getCadena("BORRAR")%>" onclick="javascript:BorraDatos('<%=j%>');"/>
<%}%>
</p>
</td>
</tr>
<tr id="iden<%=j%>"><td valign="top" colspan="2">
<p class="filacmp">
<span class="cmpeti"><%=GestorIdioma.getCadena("IDENEXPUI")%>:</span>
<input type="text" class="inpuedi" name="txtsssiexpide<%=j%>" size="10" value="<%=Utilidades.dameElemHashtable(h,"txtsssiexpide" + j)%>" maxlength="3" onKeyPress="javascript:funValidarNumero();" onblur="javascript:formateaNumero(this);" <%=soloLectura%> />
</p>
</td></tr>
<tr id="deposito<%=j%>"><td valign="top" colspan="2">
<input type="hidden" name="txtissicodrsg<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"txtissicodrsg" + j)%>"/>
<input type="hidden" name="mastamdep<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"mastamdep" + j)%>"/>
<input type="hidden" name="masgesaut<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"masgesaut" + j)%>"/>
<p class="filacmp">
<span class="cmpeti"><%=GestorIdioma.getCadena("DEPOSITO")%>:</span>
<input type="text" class="inpuedi" name="masDBreve<%=j%>" size="30" value="<%=encodeHTML(Utilidades.dameElemHashtable(h,"masDBreve" + j))%>" readonly="readonly"/>
<input type="text" class="inpuedi" name="masDDescri<%=j%>" size="40" value="<%=encodeHTML(Utilidades.dameElemHashtable(h,"masDDescri" + j))%>" readonly="readonly"/>
<%if(!Utilidades.dameElemHashtable(h,"EXPURGO").equals("S") && !Utilidades.dameElemHashtable(h,"TRANSFERENCIA").equals("S")){%>
<input type="button" name="btnCodClas" class="boton" value="..." onclick="javascript:SelDepconEspacio('DISPONIBILIDAD',document.frmDatos.txtissicodrsg<%=j%>.value,'<%=j%>')" />
<input type="button" name="btnCodClasT" class="boton" value="<%=GestorIdioma.getCadena("TODOS")%>" onclick="javascript:SeleccionarComponente('DISPONIBILIDAD',document.frmDatos.txtissicodrsg<%=j%>.value,'<%=j%>')"/>
<%}%>
</p>
</td>
</tr>
<tr id="idendeposito<%=j%>"><td valign="top" colspan="2">
<p class="filacmp">
<span class="cmpeti"><%=GestorIdioma.getCadena("CODUBICACION")%>:</span>
<input type="text" class="inpuedi" name="txtsnsirsgide<%=j%>" size="30" value="<%=Utilidades.dameElemHashtable(h,"txtsnsirsgide" + j)%>" <%=soloLectura%>/>
</p>
</td></tr>
<tr id="obser<%=j%>"><td valign="top" colspan="2">
<p class="filacmp">
<span class="cmpeti"><%=GestorIdioma.getCadena("OBSERVACIONES")%>:</span><br />
<textarea name="txtsnsiobserv<%=j%>" rows="4" cols="65" <%=soloLectura%> ><%=Utilidades.dameElemHashtable(h,"txtsnsiobserv" + j)%></textarea>
</p>
<div class="grisclaro bordeuskera" >
<p class="filareas">
<span class="cmpeti"><%=GestorIdioma.getCadena("SIGNATURA")%></span> <span class="cmpetirojo">*<%=GestorIdioma.getCadena("DATOSEUSKERA")%></span>
</p>
<div class="grisclaro">
<p class="filacmp">
<span class="cmpeti"><%=GestorIdioma.getCadena("OBSERVACIONES")%>:</span><br />
<textarea name="txtsnsiobserv<%=j%>_e" rows="4" cols="65" <%=soloLectura%> ><%=Utilidades.dameElemHashtable(h,"txtsnsiobserv" + j+"_e")%></textarea>
</p>
</div>
</div>
</td></tr>
<%}%>
</table>
</div>
</td></tr>
</table>
<%if(!Utilidades.dameElemHashtable(h,"EXPURGO").equals("S") && !Utilidades.dameElemHashtable(h,"TRANSFERENCIA").equals("S")){%>
<!-- Opciones auxiliares -->
<%# include file="../includeJSP/OpcionesMant.inc" %>
<%}%>
</form>
</body>
</html>
Finally i found a solution
window.onload = function(e){
<%if(!faltanCampos.equals("")){%>alert("<%=faltanCampos%>")<%}%>
//Ocultamos los vacios'
var j, nombre
i=<%=totalSig%>
for (j=i-1;j > 0;j--){
nombre="txtissicodtui" + j
if ( document.getElementsByName(nombre)[0].value == ""){
menos();
}
}
actualizaNivel();
}

Insert after for dynamic row

I have a dynamic adding row button. I can add more Ids and more clients but when I click on the plus it adds them in the top of my page and not after my row. How do I do that? Here is my code :
<b>Dimanche</b> </br><?php echo $date1 ?>
</td>
<!-- numéro de projet du dimanche -->
<td>
<span id="numpro" >
<form method="post" action="" onsubmit="return false;">
<input type="text" id="name" name="add_name"onkeypress="return handleEnter(event, this, 'task');"/></br>
<?php
if($result!=false && mysqli_num_rows($result)>0)
{
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>">
<input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /></p>
<?php endwhile; } ?>
</span>
<input onclick="addRow(this.form);" type="button" value="+" />
</td>
</form>
<html>
<div >
<form method="post" >
<div id="itemRows">
<?php
if($result!=false && mysqli_num_rows($result)>0)
{
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>">
<input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /></p>
<?php endwhile; } ?>
</div>
<p><input type="submit" name="ok" value="Ajouter à la B.D"></p>
</form>
</div>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'"> <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="text" name="client1[]" size="12" class = "client1" id ="client1" disabled value="'+frm.client1.value+'"><input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_client1.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
</span>
</td>
</td>
<!-- client du dimanche -->
<td>
<span id="proclient">
<input type="text" name="client1" size="12" class = "client1" id ="client1" disabled />
</span>
</td>
<!-- description du projet de dimanche -->
<td>
<span id="prodesc">
<input type="text" name="desc1" size="30" id ="desc1" class "desc" disabled />
</span>
</td>
<!-- ddescription de la tache du dimanche -->
<td>
<span id="protache">
<textarea rows="1" cols="20" name="taskDesc1" id ="task1" class "task"> </textarea>
</span>
</td>
<!-- lieu pour dimanche -->
<td>
<span id="prolieu">
<input type="text" name="prolieu1" size="10" id ="lieu1" class "lieu">
</span>
</td>
<!-- tache -->
<td>
<span id="tache">
<!-- <input type="text" name="tache" size="30" id="tache"class= "tache" /> -->
<!-- début section cobobox tache avec tool tip -->
<label title="Select your state"> <select title="Select your state" id="state" name="state">
<?php
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo ' <option title="';
echo $row['tacName'];
echo '">';
echo $row['tacId'];
echo '</option>'."\n";
$task = array();
//echo '<option value="'.$row['tacName'].'">'.$row['tacId'].'</option>'."\n";
}
?>
</select>
</label>
<!-- Fin section cobobox tache avec tool tip -->
</span>
</td>
<!-- calculter le temps pour le diamnche -->
<td>
<span id="calculTemps">
<input type="number" name="tempsd" size="30" id="temps1"class= "temps" min= "0" max="24" value="0" />
</span>
</td>
EDIT Here a demo of my problem
EDIT Here a demo of my goal I want
Try to use JQuery functions insertAfter and appendTo together with selectors :last or :first.
Common examples: jQuery('<p>').html('Some content').insertAfter('#id_here:last'); jQuery('<p>').html('Some content').appendTo('#itemRows');

Categories