0 votes

mysql update error in php form

the case is that I have a form in which when clicking on a button I can put as id_categoria 1 to the corresponding email.

if (isset($_POST['be-admin'])) {

        $user = $_POST['user'];

        $sql_admin = "UPDATE usuarios SET id_categoria = 1 where email = '".$user."'";

        mysqli_query($conexion, $sql_admin);

        //header('Location: ../../index.php');


this is the code, the $user is the email linked to the button that gives me the data perfectly, but I think the failure is in the quotes of the sql query, I have tried a thousand ways but nothing, anyone who can help me? Thank you very much in advance and greetings.


Mauricio Contreras Points 2571

You can use the functions mysqli_prepare() , mysqli_stmt_bind_param() , mysqli_stmt_execute() to achieve what you set out to do.

Using these functions your code would look like the following:

if (isset($_POST['be-admin'])) {

    $user = $_POST['user'];

    // Aqui preparas el statement con tu consulta
    // fíjate que en tu SQL query pones una
    // interrogación en el campo que vas a enlazar
    $statement = mysqli_prepare($conexion, "UPDATE usuarios SET id_categoria=1 WHERE email=?");

    // Aqui enlazas tu parámetro
    // Esta función recibe tu 'statement',
    // el tipo de variable 's' (string),
    // y la variable ($user)
    mysqli_stmt_bind_param($statement, "s", $user);

    // Ahora ya puedes ejecutar la consulta

    // Por último cierras la consulta


    //header('Location: ../../index.php');


In addition, by using these functions, you avoid a very common attack called SQL Injection, which takes advantage of the vulnerability you have in your code by directly 'concatenating' the value of your variable $user .

For example, someone could exploit this vulnerability by setting the value of $user a: some@e.mail' OR '1'='1

The query would then be passed to the server as follows:

UPDATE usuarios SET id_categoria=1 WHERE email='some@e.mail' OR '1'='1';

all records in the table are affected usuarios since '1'='1' always returns true .

Using the functions that I have suggested, this does not happen, since the function mysqli_stmt_bind_param() receives the value of $user and converts it to a string, leaving the query as follows:

UPDATE usuarios SET id_categoria=1 WHERE email='some@e.mail OR 1=1'

Here the UPDATE will have no effect, unless in your DB you have a user with such a strange email address as some@e.mail OR 1=1 .

This is one type of SQL Injection attack, there are many more. But using these functions, you avoid this type.

You can see the information on each of the methods used here:





Information about SQL Injection:

SQL Injection


HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by: