Error in MYSQL and PHP query

2

Good afternoon. I do not know why this query is not done in PHP and Mysql

This is the code of the form to send the content:

<?php
session_start();
if(!isset($_SESSION['usuario']))
{
header('Location:auth');
exit();
}
include 'conexion.php';
$usuario = $_SESSION['usuario'];
//Consulta numero de mensajes
$grupo= $_GET['grupo'];
$iii="1";
?>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Software Benedicto XVI | Software Eclesiástico SisPasIn</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" />
    <script src="js/jquery.dataTables.min.js"></script>
    <script src="js/dataTables.bootstrap.min.js"></script>
    <link rel="stylesheet" href="css/dataTables.bootstrap.min.css" />
    <script src="js/bootstrap.min.js"></script>

    <script src="js/FancyZoom.js" type="text/javascript"></script>
    <script src="js/FancyZoomHTML.js" type="text/javascript"></script>

    <script type="text/javascript" class="init">
        $(document).ready(function() {
            $('#seminaristas').DataTable();
                rowReorder: true
        } );
        $(document).ready(function() {
            $('#mensajes').DataTable();
                rowReorder: true
        } );
    </script>

<body onLoad="setupZoom()">

<div class="container">
<center><h1> <font face="Trajan Pro">Resultados</font></h1></center>
<a href="index.php"><button type="button" class="btn btn-default"> Regresar</button></a></br></br>

<form method="post" name="actualizar" id="actualizar" action="actualizar.php">
    <table id="seminaristas" class="table table-striped table-bordered" cellspacing="0" >
    <thead>
        <tr>
            <th>Apellidos, Nombre</th>
            <?php
              $sentencia=mysqli_query($conexion,"SELECT * FROM calificaciones WHERE grupo='$grupo'");
              While($resultado=mysqli_fetch_array($sentencia)){
            ?>
                  <th><?php echo $resultado['nombre_calificacion']; ?> (<?php echo $resultado['porcentaje']; ?>%)</th>
            <?php } ?>
    </thead>
    <tfoot>
        <tr>
            <th>Apellidos, Nombre</th>
            <?php
              $sentencia=mysqli_query($conexion,"SELECT * FROM calificaciones WHERE grupo='$grupo'");
              $numero = mysqli_num_rows($sentencia);
              While($resultado=mysqli_fetch_array($sentencia)){
            ?>
                  <th><?php echo $resultado['nombre_calificacion']; ?> (<?php echo $resultado['porcentaje']; ?>%)</th>
            <?php } ?>
        </tr>
    </tfoot>
    <tbody>
        <?php //carga los nombres
            $ss=mysqli_query($conexion,"SELECT * FROM seminaristas JOIN grupo_estudiante WHERE grupo_estudiante.Idg='$grupo' AND grupo_estudiante.Id=seminaristas.Id ORDER BY seminaristas.apellido, seminaristas.nombre ASC");
    $ii="1";
    While($rr=mysqli_fetch_array($ss)){
        ?>
        <tr>
            <td><?php echo $rr['apellido']; ?>, <?php echo $rr['nombre']; ?></td>

    <?php
      $sentencia2=mysqli_query($conexion,"SELECT * FROM calificaciones WHERE grupo='$grupo'");
      $i="1";
      While($resultado2=mysqli_fetch_array($sentencia2)){

        $numero_cali=$resultado2['Idcal'];
      $estudiante=$rr['Id'];

        $sentencia3=mysqli_query($conexion,"SELECT * FROM notas WHERE calificacion='$numero_cali' AND estudiante='$estudiante' AND grupo='$grupo'");
        $resultado3=mysqli_fetch_assoc($sentencia3);
      ?>

<td><input name="nota<?php echo $i; ?>[]" data-id="<?php echo $estudiante; ?>" id="nota<?php echo $i; ?>-<?php echo $estudiante; ?>" value="<?php echo $resultado3['nota']; ?>" /> <input data-id="<?php echo $estudiante; ?>" id="porcentaje<?php echo $i; ?>-<?php echo $estudiante; ?>" style="display:none" value="<?php echo $resultado2['porcentaje']; ?>" /> <input name="idnota<?php echo $i; ?>[]" id="idnota<?php echo $i; ?>-<?php echo $estudiante; ?>" style="display:none" value="<?php echo $resultado3['Idn']; ?>" /></td>
<td hidden><input name="idn[]" id="<?php echo $iii; ?>" value="<?php echo $iii; ?>" /></td>
<td hidden><input name="grupo" id="grupo" value="<?php echo $grupo; ?>" /></td>

<?php $i++; $iii++; } ?>

<td><input name="resultado[]" id="resultado-<?php echo $estudiante; ?>" value="0" readonly /></td>
<?php $ii++; } ?>
        </tr>
</table>

</th>

<input type="submit" name="actualizar" value="Guardar" class="btn btn-info col-md-offset-9" />
</form>
</div>
<script src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$('input').click(function() {
$(this).select();
});


$(document).ready(function(){
$("#actualizar").find(':input').each(function() {
var elemento= this;
var dataid = $(this).data('id');

<?php
  $sentencia2=mysqli_query($conexion,"SELECT * FROM calificaciones WHERE grupo='$grupo'");
  $i="1";
  While($resultado2=mysqli_fetch_array($sentencia2)){
  ?>
  var nota<?php echo $i; ?> = parseFloat($('#nota<?php echo $i; ?>-' + dataid).val());
  var porcentaje<?php echo $i; ?> = parseFloat($('#porcentaje<?php echo $i; ?>-' + dataid).val());
<?php $i++; } ?>

var resultado = <?php  $sentencia22=mysqli_query($conexion,"SELECT * FROM calificaciones WHERE grupo='$grupo'");
$i="1";
$numero = mysqli_num_rows($sentencia22);
While($resultado22=mysqli_fetch_array($sentencia22)){
?>(nota<?php echo $i; ?>*porcentaje<?php echo $i; ?>/100) <?php if ($i < $numero) {  echo "+"; } else { echo ""; } ?> <?php $i++; } ?>

$('#resultado-' + dataid).val(resultado);
});
});

$('input').keyup(function() {
var dataid = $(this).data('id');

<?php
  $sentencia23=mysqli_query($conexion,"SELECT * FROM calificaciones WHERE grupo='$grupo'");
  $i="1";
  While($resultado23=mysqli_fetch_array($sentencia23)){
  ?>
  var nota<?php echo $i; ?> = parseFloat($('#nota<?php echo $i; ?>-' + dataid).val());
  var porcentaje<?php echo $i; ?> = parseFloat($('#porcentaje<?php echo $i; ?>-' + dataid).val());
<?php $i++; } ?>

var resultado = <?php  $sentencia22=mysqli_query($conexion,"SELECT * FROM calificaciones WHERE grupo='$grupo'");
$i="1";
$numero = mysqli_num_rows($sentencia22);
While($resultado22=mysqli_fetch_array($sentencia22)){
?>(nota<?php echo $i; ?>*porcentaje<?php echo $i; ?>/100) <?php if ($i < $numero) {  echo "+"; } else { echo ""; } ?> <?php $i++; } ?>

$('#resultado-' + dataid).val(resultado);
})
</script>

</body>
</html>

And this is the code that executes the query.

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<?php
    include 'conexion.php';
    $grupo= $_POST['grupo'];

    $i="1";
    if(isset($nota[$i]))
    {
        for ($i = 1; $i < count($_POST['idn']); $i++)
        {
            $sentencia23=mysqli_query(
                $conexion,
                "SELECT * FROM calificaciones WHERE grupo='$grupo'"
            );
            $numero = mysqli_num_rows($sentencia23);

            $ii='1';
            $nota='nota';
            $idnota='idnota';


            $stmt = $mysqli->prepare("UPDATE notas SET nota = ? WHERE Idn = ?");

            while ($resultado23 = mysqli_fetch_array($sentencia23))
            {
                ${$nota.''.$ii}   = $_POST[$nota.''.$ii][$i];
                ${$idnota.''.$ii} = $_POST[$idnota.''.$ii][$i];

                //$result = $conexion->query(
                //  "UPDATE notas SET nota = \'$nota.''.$ii\' WHERE Idn = \''$idnota.''.$ii'\'"
                //);
                $stmt->bind_param(
                    'ss',
                    $_POST[$nota.''.$ii][$i],
                    $_POST[$idnota.''.$ii][$i]
                );

                $stmt->execute();
                $ii++;
            }
        }
    }

    //Comprobación de la actualización
    $res = ($resultado = $conexion->query($stmt))
        ? "Los datos han sido actualizados satisfactoriamente."
        : "Intente nuevamente, no se ha podido ejecutar la actualización."
            . $ejecucion->error;
    /*
    //Comprobación de la actualización
    if ($resultado = $conexion->query($stmt))
    {
        $res = "Los datos han sido actualizados satisfactoriamente.";
    }
    else 
    {
        $res = "Intente nuevamente, no se ha podido ejecutar la actualización." . $ejecucion->error;
    }
    */

    mysqli_close($conexion);
    echo $res;
?>

</html>

The errors that appear are:

  

Notice: Undefined variable: stmt in C: \ xampp \ htdocs \ seminar \ academy \ update.php on line 35

     

Warning: mysqli :: query (): Empty query in C: \ xampp \ htdocs \ seminar \ academy \ update.php on line 35

     

Notice: Undefined variable: execution in C: \ xampp \ htdocs \ seminar \ academy \ update.php on line 38

     

Notice: Trying to get property of non-object in C: \ xampp \ htdocs \ seminar \ academy \ update.php on line 38   Try again, the update could not be executed.

Thank you very much.

    
asked by Fredy Aristizábal Aristizábal 15.11.2017 в 21:45
source

1 answer

1

First of all, all the code block that performs the queries do it within a conditional block if(isset($nota[$i])) {...} , when I do not see the array defined $ note , with what will not enter NEVER !, and that's why your program does not consult anything. If you have it in the file 'conexion.php' or in others of those who pull this: bad practice, you are bringing a connection and logic in the same file (necessary data).

About the errors ...

The first 'Notice' which refers to not being defined $ stmt, is because to get the text with the result you use this variable, which was defined within the previous block: if the program Do not enter, do not denine. It can be avoided in two ways:

Solution 1

Establish a default message previously to the conditional block and move this obtaining part of 'feedback' within the conditional block. If you do not enter you have the default message.

Solution 2

Declare the variable $ stmt previously to the conditional in which it appears by assigning it a null, but if you enter the conditional you get the message: "Try again, the update could not be executed."

I would opt for option 1, which gives you an indication of what is failing and prevents the following.

The first 'Warning' is for the previous case: $ connection-> query () would not be receiving anything.

Your second 'Notice' , due to $ execution->, error, also this clear, as the array of the beginning, I do not see this variable anywhere.

The third 'Notice' comes from the previous one, you use an object syntax to try to get a value of a property from an object, but it does not exist.

You can try to adapt the following, although there are many inconsistencies in your code:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<?php
    include 'conexion.php';

    /**
     * Simulo contenido para la variable, vamos a suponer que se aceptan:
     * mañana y tarde como valores posibles
     *
     */
    $_POST['grupo'] = 'tarde';

    /**
     * Variable con contenido simulado
     *
     */
    $nota = [
        [
            'id' => 1,
            'valor' = 4
        ],
        [
            'id' => 2,
            'valor' = 8
        ],
        [
            'id' => 3,
            'valor' = 7
        ],
    ];

    //Obtener grupo
    $grupo = $_POST['grupo'];

    /**
     * Clausulas de salvaguarda
     * Permiten verificar condiciones y detienen el programa, reduciendo indentado
     *
     */
    if (! $conexion || ! is_object($conexion) || $conexion->connect_error)
    {
        die('ERR -> Hay una problema con la conexion.');
    }

    //
    //Si la ejecución llega aquí parece que tienes conexión con una BD
    //

    if ($grupo !== 'mañana' || $grupo !== 'tarde')
    {
        die('ERR -> El grupo no es válido.');
    }
    if(! isset($nota[0]))
    {
        die('ERR -> No hay notas registradas');
    }

    //
    //Si la ejecución llega aquí ya sabemos que el grupo es correcto y que
    //al menos tienes una nota en el array
    //

    $idn = count($_POST['idn']);
    if($idn<2)
    {
        die('ERR -> idn inferior a 2 -> no se pueden consultar calificaciones');
    }

    //
    //Si la ejecución llega aquí ya sabemos por lo menos la ejecución entrará
    //en el "for"
    //

    for ($i = 1; $i < $idn; $i++)
    {
        $select = "SELECT * FROM calificaciones WHERE grupo='$grupo'";
        echo('Ejecutando consulta: ' . $select . '<br>'); //traza

        $sentencia23=mysqli_query(
            $conexion,
            $select
        );
        $numero = mysqli_num_rows($sentencia23);
        echo('Existen ' . $numero . ' calificaciones para el grupo de ' . $grupo . '.<br>');


        echo('Actualizando notas...');
        $stmt = $mysqli->prepare("UPDATE notas SET nota = ? WHERE Idn = ?");
        $j=1;
        while ($resultado23 = mysqli_fetch_array($sentencia23))
        {
            ${'nota'.$j}   = $_POST['nota'.$j][$i];
            ${'idnota'.$j} = $_POST['idnota'.$j][$i];

            $stmt->bind_param(
                'ss',
                $_POST['nota'.$j][$i],
                $_POST['idnota'.$j][$i]
            );

            $stmt->execute();
            $j++;
        } //while -> Fin actualización notas

        //Comprobación de la actualización
        $res = ($resultado = $conexion->query($stmt))
            ? "Los datos han sido actualizados satisfactoriamente."
            : "Error durante la actualización.";

        /*
        //Comprobación de la actualización
        if ($resultado = $conexion->query($stmt))
        {
            $res = "Los datos han sido actualizados satisfactoriamente.";
        }
        else
        {
            $res = "Intente nuevamente, no se ha podido ejecutar la actualización." . $ejecucion->error;
        }
        */

        //Muestra resultado consultas
        echo $res;
    } //for

    mysqli_close($conexion);

?>

</html>
    
answered by 16.11.2017 в 00:03