strpos() is closing while true

Asked

Viewed 90 times

1

I loop a query. I check if the value of each record contains within any string (in the case $message). The problem is that when the value is found, in this case within the ELSE, while is closed for some reason. I need verification to continue to be done on all records, until the end of records.

$query = "select id, id_usuario texto from palavra";
$result = mysql_query($query);
while($palavras = mysql_fetch_array($result)) {
   $valor = $palavras["texto"];
   $iduser = $palavras["id_usuario"];

   if(!strpos(strtolower($mensagem), strtolower($valor))) {
      echo " não.<BR>";
   } else {
      echo " sim.<BR>";

     $query = "select nome from usuario where id = $iduser";
     $result = mysql_query($query);
     $user_dados = mysql_fetch_row($result);

   }

}

If I take the internal consultation, the loop remains normal as expected. But I need the query.

  • Your code seems to have a problem but it does not terminate while, what is the real code of Else? the ideal is to use operator === to make the comparison

  • @rray I tested here and this way the loop remains normal. I will edit the code, the "Else" has more things...

  • I understood now haha xD to break a loop use the break

  • @rray You were right, the idea is to keep going, and not stop the loop. I tidied up there.

  • Tbm I will change my answer ...

  • Calm down, you have hit the code but the text of the question not with the last comments, can edit the question and clarify.

  • 1

    The loop must continue, and not stop after finding the first occurrence.

  • Okay, the show goes on :D

  • place: $result = mysql_query($query) or die(mysql_error()) must have an error in the second query and in the while because of the reuse of $result

  • @rray vc killed the puzzle! $result reuse is in trouble. Internal query changed to $result2 and it worked, the loop continued.

  • It’s like you haven’t read or tried what I went through in my answer ini_set and the error_reporting would have gotten to the problem, because as I said in the reply provavelmente é algum erro no uso de mysql_fetch_array ou na sua query ou outra coisa próxima a isto.

  • @Guilhermenascimento I used his commands to show the error. Did not return any error. It was not a matter of error or syntax, but of programming, basically overwriting the $result variable. Thank you.

  • @Danielaccorsi ok got it =)

Show 8 more comments

3 answers

5


The problem seems to happen in the second consultation due to the reuse of the variable $result in the second consultation change her name.

To avoid false positives with the function strpos() use the operator === so it compares the value and type. Without it if the string is found at zero position your code will be diverted to the Else block incorrectly.

$query = "select id, id_usuario texto from palavra";
$result = mysql_query($query); //<--- primeira ocorrência

//aqui na segunda 'volta' do while $result já pode ser false ou não devolver as chaves texto e id_usuario
while($palavras = mysql_fetch_array($result)) { 
   $valor = $palavras["texto"];

   if(strpos(strtolower($mensagem), strtolower($valor)) === false) {
      echo " não.<BR>";
   } else {

      $query = "select nome from usuario where id = $iduser";
      $result = mysql_query($query); //reatribução indevida.
      $user_dados = mysql_fetch_row($result);
   }

}

4

Must be a Exception and the errors are off so you didn’t notice, turn on the PHP errors, when in development, in production use ini_set('display_errors', '0');, is probably some mistake in using mysql_fetch_array or in your query or something next to this.

Another problem that may have occurred was with the variable $mensagem, check if it exists and is in it "scope" from the script you quoted.

Do so in development, put at the top of your file:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL|E_STRICT);

Something else strpos only returns false if nothing is found, if you do this for example:

strpos('abc', 'a');

It will return zero and as ! considers both 0, how much false how much NULL how much '' (empty string) so it should be used like this:

   if (strpos(strtolower($mensagem), strtolower($valor)) === false) {
        echo " não.<BR>";
   } else {
        echo " sim.<BR>";

        $query = "select nome from usuario where id = $iduser";
        $result = mysql_query($query);
        $user_dados = mysql_fetch_row($result);
   }

I noticed you used strtolower, but that’s expendable if you use it like this stripos:

   if (stripos($mensagem, $valor) === false) {
        echo " não.<BR>";
   } else {
        echo " sim.<BR>";

        $query = "select nome from usuario where id = $iduser";
        $result = mysql_query($query);
        $user_dados = mysql_fetch_row($result);
   }

Another important thing is to no longer use the old PHP API for mysql, prefer PDO or mysqli, read:

  • 1

    I don’t even know what’s right, you saw this comment ? The.o

0

Your problem is because our friend PHP interprets the "0" in the same way as the "false". So when he finds the substring at the beginning of the string he returns 0 (which php also understands as false).

change your code to:

while($palavras = mysql_fetch_array($result)) {
   $valor = $palavras["texto"];

   if(strpos(strtolower($mensagem), strtolower($valor)) === false) {
      echo " não.<BR>";
   } else {
      echo " sim.<BR>";
   }

}

That’s right with 3 "===".

  • Not the same as I said?

  • Yes, when I started answering you had not yet posted, I saw it now. D

Browser other questions tagged

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