0

i ́m doing a website for managing a school centre and i have a doubt i wish you can to solve it.

I have this code:

login.php

<!doctype html>
<html lang="es">
<head>
<meta charset="iso-8859-1" />
</head>
<body>
<form action="comprobacionlogin_usuario.php" method="POST">
 <table border="1">
 <tr>
 <th>Nombre de usuario</th>
 <td><input type="text" name="usuario" autocomplete="off" required></td>
 </tr>
 <tr>
 <th>Contrase&ntilde;a</th>
 <td><input type="password" name="contrasena" autocomplete="off" required></td>
 </tr>
 <tr>
 <td></td>
 <td><input type="submit" value="Enviar"></td>
 </tr>
</table>
</form>
¿No eres usuario? Pulsa <a href="altanuevoprofesor.php">aqu&iacute;</a>
</body>
</html>

nuevo_horario.php

<?php
session_start();
$curso=$_POST['curso'];
$clase=$_POST['clase'];
?>
<html lang="es">
 <head>
 <meta charset="iso-8859-1">
 <script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript" src="administrar_filas.js"></script>
 <link rel="stylesheet" type="text/css" href="estilo_botones_tabla.css">
 Horario
 </head>
 <body>
 <div id="elementos">
 <form id="datos" action="procesar_horario.php" method="post">
 <table border="1" id="tabla">
 <thead>
 <tr>
 <td>Hora</td>
 <td>Lunes</td>
 <td>Martes</td>
 <td>Mi&eacute;rcoles</td>
 <td>Jueves</td>
 <td>Viernes</td>
 </tr>
 </thead>
 <tbody>
 <tr class="fila-base">
 <td><input type="text" name="hora_0" placeholder="Hora_0"></td>
 <td><input type="text" name="asignatura_lun_0" placeholder="Asignatura"><br><input type="text" name="id_usuario_lun_0"placeholder="Id_profesor"></td>
 <td><input type="text" name="asignatura_mar_0" placeholder="Asignatura"><br><input type="text" name="id_usuario_mar_0"placeholder="Id_profesor"></td>
 <td><input type="text" name="asignatura_mie_0" placeholder="Asignatura"><br><input type="text" name="id_usuario_mie_0"placeholder="Id_profesor"></td>
 <td><input type="text" name="asignatura_jue_0" placeholder="Asignatura"><br><input type="text" name="id_usuario_jue_0"placeholder="Id_profesor"></td>
 <td><input type="text" name="asignatura_vie_0" placeholder="Asignatura"><br><input type="text" name="id_usuario_vie_0"placeholder="Id_profesor"></td>
 <td class="eliminar">Eliminar</td>
 </tr>
 <input type="hidden" name="curso" id="curso" value="<?php echo $curso ?>">
 <input type="hidden" name="clase" id="clase" value="<?php echo $clase ?>">
 </tbody>
 </table>
 <input type="button" id="agregar" value="Agregar fila" />
 <input type="submit" id="enviar" value="Enviar">
 </form>
 </div>
 <?php
 $conexion = mysql_connect("localhost", "alonsosjumper", "alonsosjumper") or die('No se pudo conectar: ' . mysql_error());
echo '<br>Conexi&oacuten satisfactoria<br>';
mysql_select_db("proyecto", $conexion) or die('No se pudo seleccionar la base de datos');
 $consulta= "select id_usuario, nombre, apellidos from usuarios where tipo_usuario='profesor' order by id_usuario";
 $resultado= mysql_query($consulta);
 echo ' <p>Lista de profesores</p>
 <table border="1" width="auto">
 <tr><td>Id_usuario</td><td>Nombre</td><td>Apellidos</td></tr>';
 while($fila = mysql_fetch_array($resultado))
{
 echo "<tr><td>".$fila['id_usuario']."</td><td>".$fila['nombre']."</td><td>".$fila['apellidos']."</td></tr>";
}
 ?>
 </body>
</html>

procesar_horario.php

<?php
session_start();
//I wanna have here the variable "cuentaInputs" to use it in the for.
$conexion = mysql_connect("localhost", "alonsosjumper", "alonsosjumper") or die('No se pudo conectar: ' . mysql_error());
echo '<br>Conexi&oacuten satisfactoria<br>';
mysql_select_db("proyecto", $conexion) or die('No se pudo seleccionar la base de datos');
for($i=0; $i<$cuentaInputs; $i++) {
 for($j=1; $j<6; $j++)
{
 if($j==1)
 {
 $asignatura=$_POST["asignatura_lun_".$i];
 $id_usuario=$_POST["id_usuario_lun_".$i];
 $hora=$_POST["hora_".$i];
 $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";
 echo $consulta;
 }
 if($j==2)
 {
 $asignatura=$_POST["asignatura_mar_".$i];
 $id_usuario=$_POST["id_usuario_mar_".$i];
 $hora=$_POST["hora_".$i];
 $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";
 echo $consulta;
 }
 if($j==3)
 {
 $asignatura=$_POST["asignatura_mie_".$i];
 $id_usuario=$_POST["id_usuario_mie_".$i];
 $hora=$_POST["hora_".$i];
 $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";
 echo $consulta;
 }
 if($j==4)
 {
 $asignatura=$_POST["asignatura_jue_".$i];
 $id_usuario=$_POST["id_usuario_jue_".$i];
 $hora=$_POST["hora_".$i];
 $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";
 echo $consulta;
 }
 if($j==5)
 {
 $asignatura=$_POST["asignatura_vie_".$i];
 $id_usuario=$_POST["id_usuario_vie_".$i];
 $hora=$_POST["hora_".$i];
 $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";
 echo $consulta;
 }
 }
 }
$resultado = mysql_query($consulta);
mysql_close($conexion);
?>

administrar_filas.js

$(function(){
 var cuentaInputs = ($(".fila-base").length);
 $("#agregar").on('click', function(){
 $('#tabla > tbody:last').after('<tr><td><input type="text" name="hora'+cuentaInputs+'" placeholder="Hora"></td><td><input type="text" name="asignatura_lun_'+cuentaInputs+'" placeholder="Asignatura"><br><input type="text" name="id_usuario_lun_'+cuentaInputs+'"placeholder="Profesor"></td><td><input type="text" name="asignatura_mar_'+cuentaInputs+'" placeholder="Asignatura"><br><input type="text" name="id_usuario_mar_'+cuentaInputs+'"placeholder="Profesor"></td><td><input type="text" name="asignatura_mie_'+cuentaInputs+'" placeholder="Asignatura"><br><input type="text" name="id_usuario_mie_'+cuentaInputs+'"placeholder="Profesor"></td><td><input type="text" name="asignatura_jue_'+cuentaInputs+'" placeholder="Asignatura"><br><input type="text" name="id_usuario_jue_'+cuentaInputs+'"placeholder="Profesor"></td><td><input type="text" name="asignatura_vie_'+cuentaInputs+'" placeholder="Asignatura"><br><input type="text" name="id_usuario_vie_'+cuentaInputs+'"placeholder="Profesor"></td><td class="eliminar">Eliminar</td></tr>');
 cuentaInputs++;
 });
 // Evento que selecciona la fila y la elimina 
 $(document).on("click",".eliminar",function(){
 if (cuentaInputs>1)
 {
 var parent = $(this).parents().get(0);
 $(parent).remove();
 cuentaInputs--;
 }
 else
 alert("No se puede eliminar la ultima fila");
 }); 
});

I would like to have the variable "cuentaInputs" in "procesar_horario.php" to use it in for. I need it for a dynamic timetable i ́m doing which it ́s possible to add or remove rows.

How I can to pass the variable cuentaInputs from Jquery to PHP?

Thanks a lot!

asked Oct 14, 2013 at 20:36
4
  • 3
    Can you limit your code to only the parts that are significant to the problem? Nobody wants to examine such a piece of HTML and javascript. Commented Oct 14, 2013 at 20:46
  • 1
    plus. i wasnt even able to find cuentaInputs anywhere in your javascript/html code. is the variable name different? Commented Oct 14, 2013 at 20:48
  • Sorry, i forgot the code of Javascript. It´s posted now. Commented Oct 14, 2013 at 20:53
  • I would just use a hidden form element like you are doing for other things and make it with the jquery before the form submit. Commented Oct 14, 2013 at 20:55

3 Answers 3

1

after reading your comment. it seems you are trying to send a rows of data. insted of putting for element name and id like the following

name="asignatura_lun_'+cuentaInputs+'"

use array indexing

name="asignatura_lun['+cuentaInputs+']"

this way you'll get following arrays in php

$_POST['hora']
$_POST['asignatura_lun']
$_POST['id_usuario_lun'] 
//likewise for mar, mie, jue and vie

at the php side loop for hora array using foreach

foreach($_POST['hora'] as $key => $value) //use $key for referencing other arrays.
{
 for($j=1; $j<6; $j++)
 {
 if($j==1)
 {
 //use $key for referencing other arrays.
 $asignatura=$_POST["asignatura_lun"][$key];
 $id_usuario=$_POST["id_usuario_lun"][$key];
 $hora=$value; //$value is current horra
 $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";
 echo $consulta;
 }
 //same for other weekdays
 }
}

Reference: Read this question and answer.


Before Edit :

I really cant understand most of your code. Please try to use english identifiers. but on a brief look, using a hidden input element should solve your problem. add this in your form which submits to procesar_horario.php

<input type='hidden' name='cuentaInputs' id='cuentaInputs'/>

you can update its value whenever you update cuentaInputs.

$('#cuentaInputs').val(cuentaInputs);
answered Oct 14, 2013 at 21:00
Sign up to request clarification or add additional context in comments.

5 Comments

Although a more appropriate way will be to have a method submit the form and let that method prepare the values which needs to be sent to the server. check api.jquery.com/submit . If you need help with that. please modify and minimise your code a bit considering english only folks.
It doesn´t work. I explain to you. I need this variable to count the number of rows has the table created dynamically while Jquery. I want the "cuentaInputs" variable for using it in the "for" to insert data in MYSQL.
i have updated the answer. and please Do go through Loenix's answer. Writing hora and profesor is good from user's point of view. But keep spanish or any other language only in UI. in the code/variable names, use english. It helps other english speakers working with you.
Yeah Mohit Jain, it works perfectly! Thanks a lot!!
you are most welcome. and welcome to SO as well. happy to help.
0

Jquery's ajax method will send some value to PHP like this.

$.ajax({
 type:'POST',
 url:'procesar_horario.php',
 data: {q: putVariableHere}, //put a variable you want to pass here
 success: function (response) {
 console.log('yey, we passed the variable');
 }
});

PHP:

<?php
session_start();
//I wanna have here the variable "cuentaInputs" to use it in the for.
$cuentaInputs = $_POST['q'];
answered Oct 14, 2013 at 20:46

5 Comments

OP is trying to submit a form with that php script as form processor. sending it an ajax call wont help.
True, didn't read it well enough (not surprising I think) so I jumped to the conclusion prematurely.
Sorry, I forgot post the Javascript code. It´s correct now i´ve added the javascript code with your solution? Thankss
Is not there any solution then?
i have put an answer. check that.
0

There is no sign of jQuery in your question.
If you are developing an application, make sure to understand how it works or your project is doomed to failure.

jQuery is a library for Javascript, a client side programming language, that means this is the browser the user uses that is running the code (as HTML and CSS).
PHP is a programming language running on server side, that means clearly this is running on the server.
So you can not easily interact between them just with your own mind, there is no magic in it.

Browsers can natively submit a form with a submit button.
If you want do it with jQuery (or pure Javascript), you can trigger manually the submission (e.g with jQuery $("form").submit()).
You can also use it to send data to the server with AJAX features (e.g with jQuery $.post({howifeelit:"good"})) and the server gives you some results (HTTP inside).

Other advices:

  • Prefer the international language for programming. (even if you love you mother tongue, i understand) This is more understandable and re-usable.
  • Prefer PDO to old obsolete mysql_* functions.
  • If you persist, please use mysql_fetch_assoc() instead of mysql_fetch_array(), this is lighter and you get what you want.
  • Look at one of the million tutorial on the web to learn basics. (look at PDO, include, POST and framework keywords)
answered Oct 14, 2013 at 21:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.