Run a query by clicking on the result of another query

Asked

Viewed 850 times

0

I have the following column structure from my database: account_id, name and appearance. Imagery: http://puu.sh/gYLVL/4083073484.png

I had the following code previously:

<font size="3">Por favor digite o nome do personagem que deseja Resetar a Aparencia</font>
<br><br><br>
<form method="post" action="" id="ajax_form3" class="formulario">
<label for="senha">Nome do Personagem:</label>
<input name="nome" id="nome" type="text" size="40" />
<br /><br /><br />

        <input type="submit" name="Submit" value="Resetar Aparencia!" style="cursor:pointer;">

</form>

And your PHP:

<?php
$conexao =  mysqli_connect("localhost","root","wamp","ragnarok");
    if(trim($_POST["nome"]) == "")
    {
        echo "<div class='alert alert-danger' role='alert'><img src='images/erro.png'> Por favor digite o nome do personagem!</div>";
        exit(); 
    }

    if (strlen($_POST["nome"]) < 4)
    {
        echo "<div class='alert alert-danger' role='alert'><img src='images/erro.png'> Nome curto demais!</div>";
        exit(); 
    }

    if (strlen($_POST["nome"]) > 23)
    {
        echo "<div class='alert alert-danger' role='alert'><img src='images/erro.png'> Nome grande demais!</div>";
        exit(); 
    }

    $query = "SELECT * FROM `char` WHERE name = '".$_POST["nome"]."'";
    $resultado = mysqli_query($conexao, $query) or die(mysqli_error($conexao));
    $campo = mysqli_fetch_array($resultado);
    if ($_POST['nome'] === $campo['name']) {
        $query = "UPDATE `char` SET aparencia = '1' WHERE name = '".$_POST["nome"]."'";
        $resultado = mysqli_query($conexao, $query) or die(mysqli_error($conexao));

        $Uid = mysqli_insert_id($conexao);
        echo "<div class='alert alert-success' role='alert'><img src='images/check.png'> Aparencia resetada com sucesso!</div>";    
    }
    else
    {   

            echo "<div class='alert alert-danger' role='alert'><img src='images/erro.png'> Nome do personagem inválido!</div>";


    }

    mysqli_close($conexao);
?>

Well, this code worked perfectly, took the name of the player typed in the form field, checked if it matched the name of the database and updated each field with its value. However, I am trying to change the method, instead of the person having to type the character’s name, I would like the page to list all the characters that the person has and that when the person clicked on his name, execute the query that changes the values of the fields. That is, same code only instead of input to the name, list the names as buttons. The listing of the characters and application of a button for each is easy, I already managed getting this code:

<form method="post" action="" id="ajax_form3" class="formulario">

<table class="vertical-table th">
    <tr align="center">
      <th width="10%">
      <p style="margin-top: 0; margin-bottom: 0"><font face="Verdana" size="4"><b>Escolha o personagem que deseja resetar a aparência</b></font></th>
    </tr>';
$idconta = $_SESSION['account_id'];
$sql = "SELECT name FROM `char` WHERE account_id = '$idconta' order by `char_id` ASC";
$limite = mysqli_query($db, $sql);
while ($sql = mysqli_fetch_array($limite)) {
$name = $sql['name'];
    echo '
<tr>
      <td>
      <br>
      <button style="margin-top: 0; margin-bottom: 0; font-size:3; cursor:pointer;" class="botao" id="'.$name.'">'.$name.'</button></td>
    </tr>
</table>
</form>

The problem now is, how do I stop when the person clicks on a button with the character’s name, change the database in the row of that name to change the appearance column to 1? If possible I would like to continue using the method within the form, because it returns through ajax a success message without the need to reload the page.

Current code:

<table class="vertical-table th">
    <tr align="center">
      <th width="10%">
      <p style="margin-top: 0; margin-bottom: 0"><font face="Verdana" size="4"><b>Escolha o personagem que deseja resetar a aparência</b></font></th>
    </tr>';
$idconta = $_SESSION['account_id'];
$sql = "SELECT name FROM `char` WHERE account_id = '$idconta' order by `char_id` ASC";
$limite = mysqli_query($db, $sql);
while ($sql = mysqli_fetch_array($limite)) {
$name = $sql['name'];
    echo '
<tr>
      <td>
      <br>
      <p style="margin-top: 0; margin-bottom: 0; font-size:3; cursor:pointer;"><a href="alteraraparencia.php?id="'.$sql['name'].'">'.$name.'</a></p></td>
    </tr>
</table>

PHP:

<?php
$conexao =  mysqli_connect("localhost","root","wamp","ragnarok");
mysqli_query($conexao, "UPDATE `char` SET aparencia = '1' WHERE name = " . $_GET['name'])
    or die(mysqli_error($conexao));
?>
  • Do you want to change the value of the "appearance" column when the person clicks on the name? And what value would it be changed to? Where would you take it from? Since you did not specify more details of how you would like this update to be (without updating the page / redirecting), it is difficult to indicate anything.

  • Exactly, change the appearance value when the person clicks on the name! The value would be changed from 0 to 1 in the case. This is precisely my question, how will I get the value of this button that has the name of the person and execute the query? If it were a text field you could pick up by the $_POST method but as it is a boot as I get this value?

  • Any answers solved the problem? Don’t forget to accept any.

1 answer

2

The question has been edited and shows that there are several problems. In fact every question is compromised.

You have two big problems, among several small ones that I won’t even try to solve.

The first big problem is that you’re not listing the characters. Since the original question is not about this, I will not go into detail about this. Open another question to solve this problem.

The second is what I’m going to focus on because it was the original intent of the question.


To list the items you have to put one link to this name and call another page to display it. I won’t even complain about the old style of your HTML. So:

<p style="margin-top: 0; margin-bottom: 0"><font face="Verdana" color="#009900" size="3">
    <a href="mostraitem.php?id=' . $linha['account_id']. '>'.$name.'</a></font></p></td>

Since you didn’t put many details on the table, I can’t show you any more details either. As I said above, open another question to solve this problem.

Done this, on the page that will perform the update you will do so, in a more naive way that is the way you are probably doing:

$conexao =  mysqli_connect("localhost","root","wamp","ragnarok");
mysqli_query($conexao, "UPDATE `char` SET aparencia = '1' WHERE account_id = " . $_GET['id'])
    or die(mysqli_error($conexao));
//aqui você fará um tratamento do erro se não der certo. Mostrar uma mensagem de erro amigável
//Esse die pode ser bom em casos de falha generalizada ou para testes
//mas nunca deveria ser usado em qualquer coisa séria.

But if you want it safer, you can do it this way:

$query = mysqli_prepare($db, "UPDATE `char` SET aparencia = '1' WHERE account_id = ?");
mysqli_stmt_bind_param($query, $_GET['id']);
mysqli_stmt_execute($query);

I put in the Github for future reference.

I strongly recommend reviewing your insecure code, all of them. I realize that you don’t care about this, just put up passwords exposed on the internet.

  • I have already made this redirect to another page, in which I put messages to warn if everything went well or gave error. The problem is that I don’t know what to put in the following query: $query = "UPDATE table SET aparencia = '1' WHERE name = ?"; because I don’t know how to make him get this name value when the person clicks the button with the desired name. I would only know how to do this method if the person typed the name in a form, because it would look like this: $query = "UPDATE table SET aparencia = '1' WHERE name = '".$_POST["name"]."'"; understands?

  • On the table I took a print to avoid confusion: http://puu.sh/gYLVL/4083073484.png

  • @Guilherme as bigown said, you exchange the ID, for your key field in the case for your account_id and then you can do your SQL (example): $id = (int) $_GET['id']; UPDATE tabela SET aparecia='1' WHERE account_id = $id;

  • First: if the account_id is - and I suspected it was - your primary key, the code you showed is not doing what you say to do. Second: what you are talking about now makes the question clearer but perhaps not as clear as it should have been, it should have been put in it, and it can still be put. If you have the code of what you want to do almost ready, it is it that you should put. Third: Not knowing how the name is coming to the page that will update, can not answer.

  • So even the code you put in would help elucidate this, but only it would show how it’s sending the information, which is not the case. Make the necessary edits and I improve the response.

  • @bigown made the necessary edits I believe. I hope so it becomes easier to understand the goal.

  • The code has several problems. You’re learning to do things in half, and then you’re evolving wrong and creating more and more weird code. This is a widespread problem that will get worse every day that you insist on doing new things without understanding how it all works. Following cake recipes don’t usually work except on very simple things, standardized to the extreme, and that the original recipe is very good. It’s not the case what you’re doing. Specifically in the focus of your problem, among other problems, is the fact that the page tries to solve many things.

  • You should have a page to list the characters and another page/script to make the update, even after you call again the page that lists the characters again. There is an indicative that you want to use AJAX. It might be a good one, and it’s all the more reason to have a script Separate PHP to handle the change. Note that in the original question there was even this intention to use AJAX and even now is not using. I’m not going to focus on this. I’m going to edit the answer a little bit better but I don’t think it will be the definitive solution.

  • @bigown About the not listing of the characters I did not understand, because they are perfectly listed: http://puu.sh/gYP33/1fcfe5852c.png I’m just not getting your answer, because you wrote Para listar os itens tem que colocar um link para este nome e chamar outra página para mostrá-lo. but how so if they are already listed? What password did I make available here on the site? Only if you are talking about the localhost SQL password... I’m very beginner so the code is getting a lot of things, if you know a better method to restructure the code please send me

  • I also don’t understand why it appears, the code doesn’t seem to do this. Either you’re using something else or he’s so confused, you can’t tell it’s happening. The fact that you try to do two things at once doesn’t help. If you’re listed, are you doing what you want? The problem was just the UPDATE? So forget that part. I don’t think it’s right, but like I said, not solving the confusion of your code makes it hard to communicate. I know a better method but you will need a complete course or someone to do everything for you.

  • The problem is no longer listing this part is working perfectly. The goal now would be to click on the name maria, update the appearance in the SQL table where the name is maria to 1. As I wrote in the edited question, if it was with a post method it would be ridiculous of easy, but now using buttons instead of inputs type text I don’t know how to do understand?

  • So that’s what I put in the answer. It’s really very easy, at least when the code is organized. Disorganization makes everything more difficult. Of course I had done upon the original. try to do first with a link simple, then think of a button. As I said, separate the problems. This question is to p/ resolve the issue of updating the dice on top of the character list. Then if you still have problems doing this via a button, you ask another question, because for the database, it doesn’t matter if it’s a button or not.

  • @bigown I edited the question with the result of the current code. I believe I made the edits correctly, but when clicking on the name nothing happens.

  • I would do that, and I know it works. The fact that it is not working can be by numerous factors and you would have to pass better information to try to figure out the problem. But I saw that you’re using the name as canonical information, which is more of a problem in the architecture of your code. All right, it shouldn’t be exactly why this problem is happening (but it might be), but it will end up causing other problems in the future.

  • Taking into account that each account_id can have more than one name, I believe that This information has to be linked to the column name would not be?

  • The confusion is already there, the table as a whole is weird. I don’t even understand why this table is like this. But a name as a canonical information is never a good idea. But this is another problem. I don’t know how else to help in this matter, I gave the solution that works but it needs to be applied correctly. I can’t help you any more without understanding. I mean, this question already goes into the problem of not being clear or being too broad, because I can only guarantee that it works if I do all this software for you.

Show 11 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.