Get data through POST to PHP from a MYSQL SQL query

0

**

Hello good day, I wanted to know how I can get a value of a query by means of post to send it to a php.

What happens is that in the example code that I followed ( Link ) only sends 3 data of different combobox and I occupy a 4th variable to be able to complete a clause WHERE of a Mysql query.

I leave illustrative images:

If I try to send the same data again, it does not insert me, but if I only change the teacher, I select the same subject and student if it inserts me since I would not compare that the idmateria does not exist.

The value I need to obtain is the idmateria I get it along with other values in the query in docente_alumno.php , but in the value of combobox I put iddocente since I need it for the clause of the combobox matter.

Something like this:

SELECT COUNT(*) AS 'total'FROM notas n
inner join alumno_cuatrimestre_materia a
on n.idalumno_cuatrimestre_materia = a.idalumno_cuatrimestre_materia
WHERE (n.idalumno_cuatrimestre_materia =:alumno AND iddocente_materia =:materia )OR (n.idalumno_cuatrimestre_materia =:alumno and idmateria = :IDMATERIA);

I do not know if I made myself understood, try putting a combobox hidden but I do not send it to the php.

Code:

docente_alumno.php

<?php
include_once '../funciones/Sesiones.php';
if (!($_SESSION['tipo'] == 1)){
    header("Location:home.php");
}else{
    include_once '../funciones/Conexion2.php';
    $docente = '';
    //Consulta donde obtengo  el nombre del maestro y su iddocente, iddocente_materia y el idmateria (este ultimo lo ocupo enviar para la clausula where)
    try{
        $query = "
	SELECT concat(p.nombre,' ', p.apellido_p,' ', p.apellido_m) as Nombre, dm.iddocente, iddocente_materia, idmateria FROM docente d
    inner join persona p on d.idpersona = p.idpersona
    inner join docente_materia dm on d.iddocente = dm.iddocente
    where d.idpersona = p.idpersona and dm.estatus = 1 group by p.idpersona ORDER BY Nombre ASC
";
        $statement = $connect->prepare($query);
        $statement->execute();
        $result = $statement->fetchAll();

        foreach($result as $row) {
            $docente .= '<option value="'.$row["iddocente"].'">'.$row["Nombre"].'</option>';
        }
    }catch (Exception $e){
        echo "Error: ".$e->getMessage();
    }
    include_once 'header.php';
    include_once 'barra.php';
    include_once 'navegacion.php';
    ?>

    <div class="content-wrapper">
        <section class="content-header">
            <h1 style="text-align: center">
                Asignar Alumnos
            </h1>
        </section>
        <section class="content">
            <div class="box">
                <div class="box-header with-border">
                    <h3 class="box-title">Cargar alumno</h3>
                    <div class="box-tools pull-right">
                        <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip"
                                title="Collapse">
                            <i class="fas fa-minus"></i></button>
                    </div>
                </div>
                <div class="box-body">
                        <form method="post" id="insert_data">
                            <select name="docente" id="docente" class="form-control action" required>
                                <option value="">- Selecciona un docente -</option>
                                <?php echo $docente; ?>
                            </select>
                            <br />
                            <select name="materia" id="materia" class="form-control action" required>
                                <option value="">- Selecciona una materia -</option>
                            </select>
                            <br />
                            <select name="alumno" id="alumno" multiple class="form-control" required>
                            </select>
                            <br />
                            <input type="hidden" name="hidden_alumno" id="hidden_alumno" />
                            <button type="submit" name="insert" id="action" value="Insert" class="btn btn-primary"><i class="fas fa-upload"></i> Cargar alumnos</button>
                            <button type="button" class="btn btn-danger" id="cancelar"><i class="fas fa-ban"></i> Cancelar</button>
                        </form>
                </div>
            </div>
        </section>
    </div>
    <?php
    include_once 'footer.php';
    ?>
    <script src="js/insertar-docente-alumno.js"></script>
<?php } ?>

insert-teacher-student.js

function init(){

    docenteAlumno();

    $("#cancelar").on('click',function () {
        window.location.href="listado-docente-alumno.php";
    });

    $("#docente-cancelar").on('click',function () {
        history.go(-1)
    });
}


function docenteAlumno(){
    $('#alumno').lwMultiSelect({
        addAllText:'Agregar todos',
        removeAllText:'Limpiar',
        selectedLabel:'Seleccionados',
    });

    $('.action').change(function(){
        if($(this).val() != '')
        {
            var action = $(this).attr("id");
            var query = $(this).val();
            var result = '';
            if(action == 'docente')
            {
                result = 'materia';
            }
            else
            {
                result = 'alumno';
            }
            $.ajax({
                url: '../funciones/modelo-docente-alumno.php',
                type: 'POST',
                data:{action:action, query:query},
                success:function(data)
                {
                    $('#'+result).html(data);
                    if(result == 'alumno')
                    {
                        $('#alumno').data('plugin_lwMultiSelect').updateList();
                    }
                }
            })
        }
    });

    $('#insert_data').on('submit', function(event){
        event.preventDefault();
        //Alertas en caso de que un combobox no se seleccione (no funciona porque use el atributo required en los combobox)
        if($('#docente').val() == '')
        {
            alert("Please Select docente");
            return false;
        }
        else if($('#materia').val() == '')
        {
            alert("Please Select materia");
            return false;
        }
        else if($('#alumno').val() == '')
        {
            alert("Please Select alumno");
            return false;
        }
        else
        {
            // Aqui envia al php
            $('#hidden_alumno').val($('#alumno').val());
            var form_data = $(this).serialize();

            $.ajax({
                url: '../funciones/modelo-docente-alumno.php',
                type: 'POST',
                data:form_data,
                success:function(data) {
                    console.log(data);
                    if (data == 'done') {
                        $('#alumno').html('');
                        $('#alumno').data('plugin_lwMultiSelect').updateList();
                        $('#alumno').data('plugin_lwMultiSelect').removeAll();
                        $('#insert_data')[0].reset();
                        alert('Data Inserted');
                    }
                }
            });
        }
    });

}

init();

model-teacher-student.php

<?php

if(isset($_POST['action']))
{
    include_once 'Conexion2.php';
    $output = '';


    //Si el combobox de docente esta seleccionado
    if($_POST["action"] == 'docente')
    {
        //Ejecuta consulta sql donde obtiene X materias dependiendo del id del docente capturado en el combobox docente.
        $query = "
        select nombre, dm.* from materia m
        inner join docente_materia dm on m.idmateria = dm.idmateria
        inner join docente d on dm.iddocente = d.iddocente
        where dm.iddocente = :docente and dm.estatus = 1
        group by nombre
		";
        $statement = $connect->prepare($query);
        $statement->execute(
            array(
                ':docente'		=>	$_POST["query"]
            )
        );
        $result = $statement->fetchAll();
        $output .= '<option value="">- Selecciona una materia -</option>';
        //Rellena el combobox con X opciones dependiendo el resultado de la consulta a materias
        foreach($result as $row)
        {
            $output .= '<option value="'.$row["iddocente_materia"].'">'.$row["nombre"].'</option>';
        }
    }

    //Si el combobox de materia esta seleccionado
    if($_POST["action"] == 'materia')
    {
        //Ejecuta consulta sql donde obtiene X alumnos dependiendo del id de la tabla docente_materia capturado en el combobox materia.
        $query = "
		select concat(p.nombre,' ', p.apellido_p,' ', p.apellido_m) as Nombre, idalumno_cuatrimestre_materia from alumno_cuatrimestre_materia acm
        inner join alumno_cuatrimestre a on acm.idalumno_cuatrimestre = a.idalumno_cuatrimestre
        inner join alumno a2 on a.idalumno = a2.idalumno
        inner join persona p on a2.idpersona = p.idpersona
        inner join docente_materia dm on dm.idmateria = acm.idmateria
        where acm.estatus = 1 and dm.iddocente_materia = :materia
		";
        $statement = $connect->prepare($query);
        $statement->execute(
            array(
                ':materia'		=>	$_POST["query"]
            )
        );
        $result = $statement->fetchAll();
        //Rellena el combobox con X opciones dependiendo el resultado de la consulta a alumno_cuatrimestre_materia
        foreach($result as $row)
        {
            $output .= '<option value="'.$row["idalumno_cuatrimestre_materia"].'">'.$row["Nombre"].'</option>';
        }


    }
    echo $output;
}

// Para insertar
if(isset($_POST['docente']))
{
    include_once 'Conexion2.php';
    //separa la cadena enviada delimitandola hasta la ',' del input hidden_alumno
    $ciudades = explode(",",$_POST["hidden_alumno"]);
    //foreach para dividir la cadena POST
    foreach ($ciudades as &$valor) {
        //Consulta sql para verificar si alguno de los alumnos seleccionados existe en la tabla notas, de ser asi no inserta ninguno.
        $sql = $connect->prepare("SELECT COUNT(*) AS 'total' FROM notas n
                              inner join alumno_cuatrimestre_materia a on n.idalumno_cuatrimestre_materia = a.idalumno_cuatrimestre_materia
                              WHERE n.idalumno_cuatrimestre_materia =:alumno AND iddocente_materia =:materia");
        $sql->execute(
            //Aqui van las variables:
            //:materia-> contiene el iddocente_materia de la relacion entre un docente y una materia
            //:alumno-> contiene los id's de los alumnos seleccionados desde la tabla alumno_cuatrimestre_materia.
            array(
                ':materia'       =>  $_POST['materia'],
                ':alumno'        =>  $valor
            )
        );
        $result = $sql->fetchObject();
        //Si la consulta de verificacion recibe un valor > 0 no inserta
        if ($result->total > 0)
        {
            echo 'error, ya existe ';
        }
        else
        {
            //De lo contrario inicia la inserción de registros.
            $query = "INSERT INTO notas (iddocente_materia, idalumno_cuatrimestre_materia)
	              VALUES(:materia, :alumno)";
            $statement = $connect->prepare($query);
            $statement->execute(
                array(
                    ':materia'       =>  $_POST['materia'],
                    ':alumno'        =>  $valor
                )
            );
            $result = $statement->fetchAll();

        }
        if(isset($result))
        {
            echo 'insertado correctamente ';
        }
    }
}
    
asked by Member 26.07.2018 в 04:32
source

1 answer

1

As @A.Cenado commented I just put an id assigning the idmateria of my query in that part to the options generated in combobox matters

foreach($result as $row)
        {
            $output .= '<option id="'.$row["idmateria"].'" value="'.$row["iddocente_materia"].'">'.$row["nombre"].'</option>';
        }

and add another hidden input after input hidden_alumno

<input type="hidden" name="hidden_idmateria" id="hidden_idmateria" />

later when sending by ajax to the php just add:

$('#hidden_idmateria').val($('#materia option:selected').attr("id"));

and with that I could already receive the id of the subject selected by POST in the php to perform the validation of the query.

I do not know if it's the right way but for now it worked for me.

    
answered by 26.07.2018 / 05:18
source