Comparison between PHP and mysql variables

2

I have no idea how to do a 'comparison' between 2 variables in the example below: **

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

So long as the id is equal to what is in mysql it will work, but it will have multiple ids separated by commas, eg 'aaa,bbb,ccc,ddd' and I would like to know if it is possible for 'comparison' to go through all lines of the string in mysql and see if it finds something equal to the individual lock variable (idBlock).

    
asked by anonymous 03.07.2018 / 20:50

3 answers

5

You can solve this problem by converting this string ( $row['block'] into an array with the function explode() and then comparing it with in_array() if the specified value ( $id ) exists 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';
}
    
03.07.2018 / 20:56
3

First you need to separate the values that are commas to 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 ids separated, you can loop with foreach or use the in_array function native from 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 */
}
    
03.07.2018 / 20:58
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, notice that I used object-oriented mode, that is, my variable $mysqli was created like this:

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

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

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

    
03.07.2018 / 20:58