Form to change value in the database

0

I have this in the database

IwantedaformthatbyclickingtheEnviarbuttonchangedthevalueofpontosoftheselecteduser.ButfornowIonlyhavethis,IdonotknowhowtomakethecodeinPHP.

<?php$connect=mysql_connect('xxxxxxxx','xxxxxxx','xxxxxxxxx');$db=mysql_select_db('xxxxxxx');

<form>
Qual usuário deseja mudar?<br>
  <select name="usuario">
    <option value="todos usuários do banco de dados aqui">todos usuários do banco de dados aqui</option>
  </select><br>
 Novo valor:<br>
  <input type="text" name="pts"><br>
   <input type="submit" value="Enviar">
</form>
    
asked by anonymous 23.12.2018 / 16:02

2 answers

0

The old mysql_* functions have been removed from PHP . You must use mysqli_* or PDO . I'll make an example using MySQLi structured.

  

But for now I only have this, I do not know how to make the code in PHP

1) A simple way is to make a file with the database connection and include it where and when you need it:

File db.php connection :

<?php

$conexao = mysqli_connect(
    // Altere conforme necessário
    'xxxxxxxx',    // Host do banco de dados
    'xxxxxxxx',    // Usuário
    'xxxxxxxx',    // Senha
    'xxxxxxxx'     // Nome do banco de dados
);

if (mysqli_connect_errno()) {
    printf(
        'Erro na conexão com o banco de dados: %s',
        mysqli_connect_error()
    );
    die();
}

2) View users in select :

index.php file :

<?php

require_once('conexao_db.php');

$query = mysqli_query($conexao, 'SELECT * FROM 'usuarios';');

$usuarios = mysqli_fetch_all($query, MYSQLI_ASSOC);

?>

<form action="/setpontos.php" method="post">
    Qual usuário deseja mudar?<br>
    <select name="usuario">
        <?php
        foreach ($usuarios as $usuario) { ?>
            <option value="<?= $usuario['ID']; ?>"><?= $usuario['login']; ?></option>
        <?php
        } ?>
    </select><br>
    Novo valor:<br>
    <input type="text" name="pts"><br>
    <input type="submit" value="Enviar">
</form>

3) Note that in index.php , action of form is the setpontos.php file and the method is post . Let's do this file now

File setpontos.php :

<?php

require_once('conexao_db.php');

$sql_query = (
    "UPDATE 'usuarios'
    SET 'pontos' = '".$_POST['pts']."'
    WHERE 'ID' = '".$_POST['usuario']."';"
);

if (!($query = mysqli_query($conexao, $sql_query))) {
    printf(
        'Erro ao executar consulta no banco de dados: %s',
        mysqli_error($conexao)
    );
} else {
    echo 'Pontos do usuário definidos com sucesso!';
}

If you " Ctrl+C " Ctrl+V "correctly, everything should work. Remember that all files must be in the root directory.

Project available in my GitHub / lipespry / sopt-form-change-user-points .

Is this the best way? No. But it will be a kick-start for you to understand how it works.

    
23.12.2018 / 16:51
-1

23.12.2018 / 16:31