Form, PHP and MYSQL - mysqli_num_rows always equal to zero

Asked

Viewed 482 times

1

Fellas, I’m doing a pro bono job for a public service, and I’ve been trying for days to figure out what’s wrong with my code. If anyone can help me, I really appreciate it.

O formulário é esse:

<html>

<style>

::-webkit-input-placeholder  { color:#CDCDCD; }
input:-moz-placeholder { color:#CDCDCD; }
textarea:-moz-placeholder { color:#CDCDCD; }

</style>


<form name="saque" action="https://equadsaude.000webhostapp.com/bancodados_atualizar.php" method="POST">

<table>

<tr>
<td>Processo</td>         </tr>

<tr>
<td><input name="n1" placeholder="somente algarismos"></td>
</tr>

<tr>
<td>Valor total sacado</td>   </tr>

<tr>
<td><input name="n4" placeholder="00000.00"></td>
</tr>

<tr>
<td>Observações e Data </td> </tr>

<tr>
<td><input type="text" name="n3" ></td>
</tr>

<tr>
<td col span="3"><input type="submit" name="submit" value="Atualizar"></td>
</tr>
</table>
</form>
</html>

And the file . php (which is on the local server) that he should call is this:

     <?php

$conectar = new mysqli("localhost","id1019345_dados_zzzz","xxxx", "id1019345_sobras") or die(mysqli_error());

    $processo = $_POST[ 'n1' ] ;
    $valor_sacado = $_POST[ 'n4' ] ;
    $observacoes = $_POST[ 'n3' ] ;

    //variavel de teste do POST no banco de dados
    $teste = mysqli_query($conectar, "SELECT 'id' FROM 'Tab_Index' WHERE 'Processo' = '$processo' ");
    while (mysqli_num_rows($conectar, $teste) == 0)
    {
    echo "<p>Não existe o registro informado. Verifique novamente no Banco de Dados.</p>";  exit(mysqli_error());
    }


    //variavel para cálculo do Valor da Sobra no banco de dados
    $sql_seleciona = mysqli_query($conectar, "SELECT 'Valor_sobra' FROM 'Tab_Index' WHERE 'Processo' = '$processo' ");
    while ($query_row = mysqli_fetch_assoc($conectar, $sql_seleciona))
        {
        foreach($query_row as $key => $value)
                           {
                           $resultado = $value-$valor_sacado;
                           }
        }

    //variavel para selecao das Observacoes no banco de dados
    $sql_seleciona2 = mysqli_query ($conectar, "SELECT 'Observacoes' FROM 'Tab_Index' WHERE 'Processo' = '$processo' ");
    while ($query_row2 = mysqli_fetch_assoc($conectar, $sql_seleciona2))
        {
        foreach($query_row2 as $key => $value)
                           {
                           $resultado2 = $query2."/". $observacoes;
                           }

         }

    //Update do banco de dados
    $sql_alterar = mysqli_query($conectar, "UPDATE 'Tab_Index' SET 'Valor_sobra' =  '$resultado1', 'Observacoes' =  '$resultado2' WHERE 'Processo' = '$processo' ");

    if  ( isset ($sql_alterar) )
    {
    print "<h3> Valor da sobra atualizado com sucesso </h4>\n" ;
    }
    else 
    { 
    print "<h3> Erro ao atualizar </h4>\n" ;
    }


      ?>

The problem is that the message always appears " There is no informed record. Check again in the database.", which I put as a warning if you did not find anything in the database. But even when I put a Process number that exists in the database, it keeps giving that information. And if I remove from the script this conference, appears the final message "Surplus value updated successfully", as if there had been the database Update, but when I go to check the database, nothing has changed.

The impression I have is that the interaction with the database is not taking place, for some reason I do not know what is.

The table in DB has 4 columns: id, Process (BIGINT), Value_leftover (DECIMAL 7.2), Observations (VARCHAR). HOST: localhost USERNAME: id1019345_dados_zzzz PASSWORD: xxxx DB: id1019345_leftovers

1 answer

1

Dude, first of all, never ever pass a direct form string in the query like that. The correct way, using mysqli is as follows:

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}

reference: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php

Now let’s get down to the problem:

At the time of picking up the amount of lines that came back, you just need to pass the query result, you don’t need the connection. That is to say:

$resultado = mysqli_query($conectar, "SELECT * FROM teste");
$linhas = mysqli_num_rows($resultado);
echo $linhas; // 256

reference: http://php.net/manual/en/mysqli-result.num-rows.php

This is because the object returned to the result variable will be used in the count, the connection to the database is no longer necessary, only if you are going to do another query.

The other problem

Only even the check is wrong after yours UPDATE, why are you checking whether the variable has been set at some point (isset()). Even if he cannot perform the operation, the variable was set yes, only for a very effective value: FALSE! Only, since your question was "Is this variable set?" it will always return TRUE and proceed to the block within the condition.

Then the correct form can be two:

if ($sql_alterar) {
  (...)
}

That I don’t like personally because it’s not very clear what you’re checking, but surely it will go pro else if you can’t do the UPDATE. I prefer it that way:

if ($sql_alterar !== false) {
   (...)
}

'Cause then I’m sure, by the time I hit my eye, I’m worried if that variable is fake.

Browser other questions tagged

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