Update that does not modify the table

1

NEW CODE

VERY COMMENTED to explain where it works and where it does not!

<?php
session_start();
ob_start();
// Include config file
require_once '990conn.php';
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sin título</title>
<link href="css/sbg.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
require_once '990conn.php';
//OBTENGO el 98idusr (alias id) que me manda la pagina anterior es número PERFECTO
    if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
        // Get URL parameter
        $id =  trim($_GET["id"]);
        echo $id; //muest5ro el id
//A quien le voy a cambiar el grupo, obvio al dueño del id = $id = 98idusr PERFECTO
$sql098a="select * from $t98 WHERE 98idusr = '$id'";
if($result098a = $mysqli->query($sql098a)){
    if($result098a->num_rows == 1){
        while($row098a = $result098a->fetch_array()){
//muestro el nombre del usuario al que le voy a cambiar el grupo PERFECTO
                echo "<td><strong>" . $row098a['98nomb'] . "</strong></td>"; 
        }
        // Free result set POR LAS DUDAS LO COMENTE, NO VAYA A CERRAR NADA
//        $result098a->free();
    } else{
        echo "No hay coincidencia en la búsqueda.";
    }
} else{
    echo "ERROR: Could not able to execute $sql098a. " . $mysqli->error;
}
    }
?>  
<table width="280" border="0" cellspacing="0" cellpadding="0"><tbody><form action="098usuarios.php" method="post" target="_self" class="row" title="f098">
<!-- Selecciono el grupo dinamicamente de la tabla $t98g = 98gr que solo contiene dos columnas idgr (numérica) y gr (nombre del grupo) -->
<tr><td><select name="grupo" required  id="grupo" form="f098" title="grupo" ><option value="">Seleccione nuevo grupo</option>
<?php $sql098b="select idgr, gr from $t98g"; //$t98g es el alias de la tabla 98gr
$r098b=mysqli_query($mysqli, $sql098b); 
while($rw098b=mysqli_fetch_array($r098b)) { 
?>
<option value="<?php echo $rw098b['idgr']; ?>"><?php echo $rw098b['gr']; ?></option><?php }?>
</select></td></tr>
<tr>
<!-- Botón submit que DEBERIA cambiar el grupo NO PARECE QUE FUNCIONARA, no dice error ni cambia la pagina -->
<td><input name="bt-098" type="submit" class="btn-primary" id="bt-098" form="f098" formaction="098usuarios.php" formmethod="POST" title="bt-098" value="CAMBIAR GRUPO"></td>
<!-- Por las dudas verifico que el id = 98idusr sigue firme como rulo de estatua en el html-->
<input  name="id" value="<?php echo $id; ?>"/>
</tr></form></tbody></table>
<?php
// verificar que el boton SUBMIT fue presionado Y PARECE QUE NO, PORQUE NO CAMBIA EL GRUPO
if(isset($_POST['bt-098']))
{
// Archivo de conexion mysqli sale de aqui
require_once '990conn.php';
// seleccionar la variable que se va a actualizar grupo = 98grupo también un número definida en la selecion 
$grupo = $_POST['grupo'];
$sql098 = "UPDATE $t98 SET 98grupo = '$grupo' WHERE 98idusr='$id'"; //$t98 es el alias de la tabla 98usr
if($mysqli->query($sql098) === true){
    echo "El grupo fue cambiado.";
} else{
    echo "ERROR: No es posible ejecutar $sql098. " . $mysqli->error;
}
}
// Close connection
$mysqli->close();
?>
</body>
</html>

Good afternoon, good Sunday! After all the challenges of Cedano because I do not use prepared or parameterized queries! I put together a code that would presumably make him happy, full of those little things.

But do not go t1 tables 98usr (multiple fields only interest me 98idusr, 98nomb, 98group # [this is the one I want to update]) 98gr (only contains idgr # and gr txt because people do not memorize stupid and I do not want to walk wandering a lot with antics)

The code brings an id from another page that was nice and finally I managed to send only the id = 98idusr here all right.

Go code with all the elegance that characterizes me (do not criticize much) PROBLEM: DO NOT LOAD IN THE BOARD 98idusr the new idgr.

I'm all little glasses. Thank you! PREVIOUS CODE     

// Include config file
require_once '990conn.php';

// Define variables and initialize with empty values
$grupo = "";
$grupo_err = "";

// Processing form data when form is submitted
if(isset($_POST["98idusr"]) && !empty($_POST["98idusr"])){
    // Get hidden input value
    $id = $_POST["98idusr"];

    // Validate grupo
    $input_grupo = trim($_POST["98grupo"]);
    if(empty($input_grupo)){
        $grupo_err = "Elija un grupo.";     
    } elseif(!ctype_digit($input_grupo)){
        $grupo_err = 'Please enter a positive integer value.';
    } else{
        $grupo = $input_grupo;
    }
    // Check input errors before inserting in database
    if(empty($grupo_err)){
        // Prepare an insert statement
        $sql098 = "UPDATE 98usr SET 98grupo=['idgr'] WHERE 98idusr=?";

        if($stmt = $mysqli->prepare($sql098)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("i", $param_grupo, $param_id);

            // Set parameters
            $param_grupo = $grupo;
            $param_id = $id;

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Records updated successfully. Redirect to landing page
                header("location: 098usuarios.php");
                exit();
            } else{
                echo "Something went wrong. Please try again later.";
            }
        }

        // Close statement
        $stmt->close();
    }

    // Close connection
    $mysqli->close();
} else{
    // Check existence of id parameter before processing further
    if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
        // Get URL parameter
        $id =  trim($_GET["id"]);

        // Prepare a select statement
        $sql098b = "SELECT * FROM 98usr WHERE 98idusr = ?";
        if($stmt = $mysqli->prepare($sql098b)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("i", $param_id);

            // Set parameters
            $param_id = $id;

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                $result098b = $stmt->get_result();

                if($result098b->num_rows == 1){
                    /* Fetch result row as an associative array. Since the result set
                    contains only one row, we don't need to use while l<em>oo</em>p */
                    $row098b = $result098b->fetch_array(MYSQLI_ASSOC);

                    // Retrieve individual field value
                    $name = $row098b["98nomb"];
 //                   $grupo = $row098b["98grupo"];
                } else{
                    // URL doesn't contain valid id. Redirect to error page
                    header("location: 098error.php");
                    exit();
                }

            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }
        }  else{
        // URL doesn't contain id parameter. Redirect to error page
        header("location: 098error.php");
        exit();
    }
}

?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>xxxxxxx</title>
    <link href="css/sbg.css" rel="stylesheet" type="text/css">
            <style type="text/css">
        .wrapper{
            width: 280px;
            margin: 0 0 0 0;
            text-align: center;
            align-self: left;
        }
    </style>
</head>
<body>
<div class=page-header-280><table width="280" heigth="28" border="0" cellpadding="0" cellspacing="0" bgcolor="#4C89C0" class="copete-bl-md"><tbody><tr>
    <td align="center">Cambiar grupo</td></tr></tbody></table>
    <div class="wrapper"  width= "280">
        <div class="container-fluid" width= 280 >
            <div class="row" widht= 280 >
                    <p>Por favor seleccione el nuevo grupo</p> 
                    <p>y presione el boton para actualizar los datos.</p>
                    <p> </p>
                <form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
                        <div class="form-group"  <?php echo (!empty($name_err)) ? 'has-error' : ''; ?>">
                            <label>Nombre  </label>
                            <strong><?php echo $name; ?></strong>
                        </div>
                    <div class="form-group" <?php echo (!empty($grupo_err)) ? 'has-error' : ''; ?>">
            <td><select name="grupo" required id="grupo" form="f098u" title="grupo" ><option value="">Elija el nuevo grupo</option>
<?php $sql098c="select idgr, gr from 98gr"; 
$r098c=mysqli_query($mysqli, $sql098c); 
while($rw098c=mysqli_fetch_array($r098c)) { 
?>
<option value="<?php echo $rw098c['idgr']; ?>"><?php echo $rw098c['gr']; ?></option><?php }?>
    </select></td>
                       <span class="help-block"><?php echo $grupo_err;?></span>
                    </div>
                    <input type="hidden" name="id" value="<?php echo $id; ?>"/>
                    <input type="submit" class="btn-primary" value="Actualizar">... 
                    <a href="098usuarios.php" class="btn-default">Cancel</a></p>
                    </form>
<?php
// Close statement
$stmt->close();

// Close connection
$mysqli->close();
?>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
    
asked by Silvia Gaviota Garcia 29.10.2017 в 22:49
source

1 answer

0

UPDATE 10-30-2017

I did a proof of concept of your code. I made the first part work, that of UPDATE .

It did not work for two reasons, apart from all what I already told you in the different updates of this answer.

First new reason for error

A strange manipulation of variables in this code block:

    // Validate grupo
    $input_grupo = trim($_POST["98grupo"]);
    if(empty($input_grupo)){
        $grupo_err = "Elija un grupo.";
    } elseif(!ctype_digit($input_grupo)){
        $grupo_err = 'Please enter a positive integer value.';
    } else{
        $grupo = $input_grupo;
    }

In my test, $grupo ended up being equal to the value id , which you use as a filter of WHERE of the query. I can not give you more details about this because the values that you collect in the POST I replaced them with handwritten values.

Second new reason for error

This is the biggest mistake.

When doing a post equality operation to bind of the variables passed in it ... we do not know what you were going through, maybe you did not pass anything ... or who knows what you passed.

I mean this:

    if($stmt = $mysqli->prepare($sql098)){
        // Bind variables to the prepared statement as parameters
        $stmt->bind_param("i", $param_grupo, $param_id);

        // Set parameters
        $param_grupo = $grupo;
        $param_id = $id;

Solution:

Pass both variables above, before the bind , so that the bind passes the real values:

        // Set parameters
        $param_grupo = $grupo;
        $param_id = $id;

    if($stmt = $mysqli->prepare($sql098)){
        // Bind variables to the prepared statement as parameters
        $stmt->bind_param("i", $param_grupo, $param_id);

With these two corrections the UPDATE should work.

Here is the test code . You must press Run-F9 to try it. You can try it, changing the value of this line:

$grupo = "Los Miserables";  /*CAMBIAR ESTE VALOR PARA PROBAR*/

for another value.

These are also partially valid previous answers

There are at least two errors in your code:

First error

$sql098 = "UPDATE 98usr SET 98grupo=['idgr'] WHERE 98idusr=?";

I imagine that you want to match the column 98group to a value stored in a variable. Then, you must also place there a sign of ? :

    $sql098 = "UPDATE 98usr SET 98grupo=? WHERE 98idusr=?";

Second error

$stmt->bind_param("i", $param_grupo, $param_id);

You must be careful when doing the binding. You must strictly observe the following rules:

  • You must pass as many values as signs of ? you have in the query. If you have two here, you must bind two values.
  • You must pass them in the order in which the signs of ? appear in the query.
  • Evidently, the variables that you pass must exist.
  • The letters after the opening parenthesis indicate the data type of each column in the database: i for integers, s for string, etc.
  • Taking this into account, we corrected the binding:

    If $param_grupo is not numeric in the database:

        $stmt->bind_param("si", $param_grupo, $param_id);
    

    On the other hand, if $param_grupo is numeric in the database:

        $stmt->bind_param("ii", $param_grupo, $param_id);
    

    If that does not work, it's because you have an error in another part of the code.

    Third error

    Do not close the connection if you are going to continue using it, for example here:

        // Close connection
        $mysqli->close(); //LA CERRASTE
    } else{
    // Check existence of id parameter before processing further
    if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
        // Get URL parameter
        $id =  trim($_GET["id"]);
    
        // Prepare a select statement
        $sql098b = "SELECT * FROM 98usr WHERE 98idusr = ?";
        if($stmt = $mysqli->prepare($sql098b)){  //PERO CERRASTE $mysqli ¿como pretendes usarla aquí?
    

    UPDATE

    Seeing that there were more errors in the code, I have written this version of the controlled code. Now, if it fails, it will tell you where and why it fails.

    <?php
    session_start();
    ob_start();
    
    // Include config file
    require_once '990conn.php';
    
    if($mysqli){
    
        // Define variables and initialize with empty values
        $grupo = "";
        $grupo_err = "";
    
        // Processing form data when form is submitted
        if(isset($_POST["98idusr"]) && !empty($_POST["98idusr"])){
            // Get hidden input value
            $id = $_POST["98idusr"];
    
            // Validate grupo
            $input_grupo = trim($_POST["98grupo"]);
            if(empty($input_grupo)){
                $grupo_err = "Elija un grupo.";
            } elseif(!ctype_digit($input_grupo)){
                $grupo_err = 'Please enter a positive integer value.';
            } else{
                $grupo = $input_grupo;
            }
            // Check input errors before inserting in database
            if(empty($grupo_err)){
    
                // Prepare an insert statement
                $sql098 = "UPDATE 98usr SET 98grupo=? WHERE 98idusr=?";
    
                if($stmt = $mysqli->prepare($sql098)){
    
                    // Set parameters
                    $param_grupo = $grupo;
                    $param_id = $id;
    
                    // Bind variables to the prepared statement as parameters
                    $stmt->bind_param("ii", $param_grupo, $param_id);
    
    
                    // Attempt to execute the prepared statement
                    if($stmt->execute()){
                        printf("%d Filas actualizadas.\n", $stmt->affected_rows);
    
                        // Records updated successfully. Redirect to landing page
                        header("location: 098usuarios.php");
                        exit();
                    } else{
                        echo "Something went wrong. Please try again later.";
                    }
    
                    // Close statement
                    $stmt->close();
    
                }else{
    
                    echo "Error en la consulta.";
    
                }
    
    
            }else{
    
                echo "No se cumplió nada de lo que evaluaste de la variable group_err";
    
            }
    
        } else {
            // Check existence of id parameter before processing further
            if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
                // Get URL parameter
                $id =  trim($_GET["id"]);
    
                // Prepare a select statement
                $sql098b = "SELECT * FROM 98usr WHERE 98idusr = ?";
                if($stmt = $mysqli->prepare($sql098b)){
    
                    // Set parameters
                    $param_id = $id;
    
                    // Bind variables to the prepared statement as parameters
                    $stmt->bind_param("i", $param_id);
    
    
                    // Attempt to execute the prepared statement
                    if($stmt->execute()){
                        $result098b = $stmt->get_result();
    
                        if($result098b->num_rows == 1){
                            /* Fetch result row as an associative array. Since the result set
                        contains only one row, we don't need to use while l<em>oo</em>p */
                            $row098b = $result098b->fetch_array(MYSQLI_ASSOC);
    
                            // Retrieve individual field value
                            $name = $row098b["98nomb"];
                            //                   $grupo = $row098b["98grupo"];
                        } else{
                            // URL doesn't contain valid id. Redirect to error page
                            header("location: 098error.php");
                            exit();
                        }
    
                    } else{
                        echo "Oops! Something went wrong. Please try again later.";
                    }
                }
            }  else{
                // URL doesn't contain id parameter. Redirect to error page
                header("location: 098error.php");
                exit();
            }
        }
    
    }else{
    
        echo "La conexión es nula";
    }
    
    ?>
    
        
    answered by 29.10.2017 / 23:49
    source