Comparison between PHP and mysql variables

Asked

Viewed 253 times

2

I don’t have much idea how to 'compare' between 2 variables in the example below:**

if ($rows['block'] == $idBlock ) {/*....*/} else {/*....*/}

Until well, because if the registered id is equal what is in mysql will work, but will have several ids separated by commas,ex: 'aaa,bbb,ccc,ddd' and would like to know if it is possible to 'compare' all lines of the string in mysql and see if you find something equal to the individual lock variable (idBlock).

3 answers

5


You can solve this problem by converting this string ($row['block'] in an array with the function explode() finally just compare with in_array() if the value ($id) available in the list of blocked items.

$blocks = explode(',', 'aa,bb,cc,dd');
$id = 'aa';

if(in_array($id, $blocks)){
    echo $id . ' existe em: $blocks';
}else{
    echo 'item não encontrado';
}
  • @Pedrohenrique your final code must stay $blocks = explode(',', $rows['block']);

3

First you need to separate the comma values so only after that you can compare one by one, see;

$ids = explode(',', $rows['block']);
// a saída sera um array: ['aaa', 'bbb', 'ccc', 'ddd']

with the ids separate you can perform a loop with foreach or use the function in_array native to the PHP.

Using foreach:

foreach($ids as $id) {
    if ($id == $idBlock) {
        /*
            trate caso os ids sejam iguais
        */
    }
}

Using in_array:

if (in_array($idBlock, $ids)){
    /* O ID existe na lista em questão */
}

1

Look at the example if each id comes from multiple records:

if($th = $mysqli->query("SELECT * FORM `sua_tabela`"){
    while($row = $th->fetch_assoc()){
       if ($rows['block'] == $idBlock ) {/
           //Seu código
       } else {
           //Seu código
       }
    }
}

This will make you go through all the records coming from the query, note that I used object oriented mode, ie my variable $mysqli was created like this:

$mysqli = new mysqli('host', 'user', 'senha', 'db');

Now if your question is that each record already comes with the ids: "aa,bb,cc..."

The correct thing to do is as the example of the other users below, using the explode with a foreach or the in_array

Browser other questions tagged

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