PHP comparator " != "

Asked

Viewed 71 times

0

I’m having some difficulty with the following code;

//Verifica Se o usuario esta cadastrado no Codelist 
$query = "select trim(loginid) loginid from yfs_user where loginid = '$USER'";
$stmt = db2_prepare($conn, $query);

db2_execute($stmt, array(10));

while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
        if ($name != $USER)
    {
        echo "<h1>Usuário $name, não encontrado.</h1>";
        die ;
    }
}

So, explaining, this code is part of a function PHP I created to check if the user exists in the database DB2. Within the While, declare the variable $name and check her in if ($name != $USER) with the comparator !=, that is, if the input is different from what is in the bank, then the code displays a message and is terminated with the function die().

However, what happens is the opposite, it goes right through this function and does not present me the message User $name unseen.

Follow the whole code if you can shed some light.

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>RETORNO DE CODELIST</title>
        <link href="../css/bootstrap.min.css" rel="stylesheet">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="../js/bootstrap.min.js"></script>
    </head>
<body>
<?php

    //Valida se campo usuario ou senha estao vazios
    //if (empty($_POST['user']) or empty($_POST['passwd']))
    //    {
               // echo "<h1><h1><br />";
   //     }

    //Variaveis
    $USER = strtolower(trim($_POST['user']));
    //$PASS = trim($_POST['passwd']);
    $USER2 = $USER{0};



//------------------------------------------------------------
//Parâmetros de Banco de Dados
$hostname = '#####';
$port = #####;
$user = '####';
$password = '#####';
$database = '#####';

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');

//Verifica Se o usuario esta cadastrado no Codelist 
$query = "select trim(loginid) loginid from yfs_user where loginid = '$USER'";
$stmt = db2_prepare($conn, $query);

db2_execute($stmt, array(10));

while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
        if ($name != $USER)
    {
        echo "<h1>Usuário $name, não encontrado.</h1>";
        die ;
    }
}




                //Contador para Nao dar problema em sobrescrever arquivos
                $ARQUIVO = "/usr/local/html/santacruz_homol/cont_delete.hits";
                $HANDLE = fopen($ARQUIVO, 'r+'); // Da Permissao para ler o Arquivo
                $DATA = fread($HANDLE, 512); // Obtem a contagem do Arquivo
                $CONTADOR = $DATA + 1; //Adiciona +1 no Arquivo
                fseek($HANDLE,0); // O Ponteiro Volta para o comeco do arquivo
                fwrite($HANDLE,$CONTADOR); //Salva o valor da variavel CONTADOR no arquivo
                fclose($HANDLE); // Fecha Arquivo

                //Escreve os XML dentro no /tmp/usuario.bp
                file_put_contents("/usr/local/html/santacruz_homol/usuario_deletado_$CONTADOR.bp", "<INFO>\n");
                file_put_contents("/usr/local/html/santacruz_homol/usuario_deletado_$CONTADOR.bp", "<DADO><NAME>$USER</NAME></DADO>\n",FILE_APPEND);
                file_put_contents("/usr/local/html/santacruz_homol/usuario_deletado_$CONTADOR.bp", "</INFO>\n",FILE_APPEND);

                // Executa Shell Script para excluir Usuario
                shell_exec("/var/www/cgi-bin/delete_user_homol_santa.sh '$CONTADOR' 1> /tmp/result_delete.txt 2> /tmp/erro_delete.txt");

                ?>
                <body>
                    <!-- Modal -->
                    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
          aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" onclick="window.location.href='../index2.php'">&times;</button>
                                    <h4 class="modal-title" id="myModalLabel">Alerta !!!</h4>
                                </div>
                                <div class="modal-body">
                                    <?php echo "<h1>Usuário $name excluido !!</h1>"; ?>
                                </div>

                            </div>
                        </div>
                    </div>              
                    <script>
                        $(document).ready(function () {

                            $('#myModal').modal('show');

                        });
                    </script>

                </body>
                <?php

?>
  • Try creating a $num_rows = db_num_rows($stmt); and an if($num_rows){ echo "user exists"; }

  • tried, it didn’t work, I even took a look at the php documentation for num_rows, but I couldn’t get the result.

  • Good afternoon Wilton, is there any way to mirror the data that is sent to $USER and the data that comes in $name (Post to us)? tries to print it on the screen and see if it comes the correct data, if you have Xdebug makes it easy to find the error.

  • Good afternoon Paulo, I’m a beginner in PHP, I’m studying a lot about, I’m sorry ignorance, but I don’t know how to do this yet, have some tutorial to tell me ?

2 answers

1


I was able to solve it this way, in case I help someone with the same problem as mine !!!

<?php

    //Valida se campo usuario ou senha estao vazios
    if (empty($_POST['user']))
        {       
                echo "<h1>Campos Usuàrio Vazio<h1><br />";
                exit;
        }

    //Variaveis
    $USER = strtolower(trim($_POST['user']));


//------------------------------------------------------------
//Parâmetros de Banco de Dados
$hostname = '#####';
$port = ####;
$user = '#####';
$password = '#####';
$database = '#####';

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');

//Verifica Se o usuario esta cadastrado no Codelist 
$query = "select trim(loginid) loginid from yfs_user where loginid = '$USER'";
$stmt = db2_prepare($conn, $query);

db2_execute($stmt, array(10));

while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
        if ($name == $USER)
    {echo "Usuário $name, Excluido";}


                //Contador para Nao dar problema em sobrescrever arquivos
                $ARQUIVO = "/usr/local/html/santacruz_homol/cont_delete.hits";
                $HANDLE = fopen($ARQUIVO, 'r+'); // Da Permissao para ler o Arquivo
                $DATA = fread($HANDLE, 512); // Obtem a contagem do Arquivo
                $CONTADOR = $DATA + 1; //Adiciona +1 no Arquivo
                fseek($HANDLE,0); // O Ponteiro Volta para o comeco do arquivo
                fwrite($HANDLE,$CONTADOR); //Salva o valor da variavel CONTADOR no arquivo
                fclose($HANDLE); // Fecha Arquivo

                //Escreve os XML dentro no /tmp/usuario.bp
                file_put_contents("/usr/local/html/santacruz_homol/usuario_deletado_$CONTADOR.bp", "<INFO>\n");
                file_put_contents("/usr/local/html/santacruz_homol/usuario_deletado_$CONTADOR.bp", "<DADO><NAME>$USER</NAME></DADO>\n",FILE_APPEND);
                file_put_contents("/usr/local/html/santacruz_homol/usuario_deletado_$CONTADOR.bp", "</INFO>\n",FILE_APPEND);

                // Executa Shell Script para Inserir Usuario
                shell_exec("/var/www/cgi-bin/delete_user_homol_santa.sh '$CONTADOR' 1> /tmp/result_delete.txt 2> /tmp/erro_delete.txt");
                die;
}               

        echo "<h1>Usuàrio $USER não encontrado!!!'</h1><br />";



?>

0

It’s not better to do it instead of

while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
    if ($name != $USER)
    {
        echo "<h1>Usuário $name, não encontrado.</h1>";
        die ;
    }
}

do so, since the query searches for the $USER user in the table,

$query = "select trim(loginid) loginid from yfs_user where loginid = '$USER'";

, or so my suggestion is:

if (db2_num_rows($stmt) == 0)
{
    echo "<h1>Usuário $USER não encontrado.</h1>";
    die();
}

?

  • Oi Marcelo, also worked, thanks for the help, I’m still studying php, so are silly mistakes, but thanks for the availability !!!!

Browser other questions tagged

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