How can I check equal variables within a while

Asked

Viewed 69 times

0

How can I check equal variables within a while?

  • Like if there are lines like the same CODE do something...

A Bass put my example

$bd = new MySQLiConnection();   
$sql3 = $bd->prepare( "SELECT * FROM agenda_saidas WHERE id_transfer = ? ") or exit( $mysqli->error );
$sql3->bind_param('i', $id_transfer);
$sql3->execute();
$resultcar = $sql3->get_result(); 
while( $row = $resultcar->fetch_assoc() )
{                              
$os = $row['os'];
$nome = $row['nome'];
$data = $row['data'];


if(// se $os duplicado ){
$corlinha ='red';
}else{
$corlinha ='white';  
}

Example: Imagine these lines at the bottom

inserir a descrição da imagem aqui

  • 1

    If you take into account that there may be many duplicate codes, I think the best solution in this case is to use SQL itself and make a GROUP BY with the ID field, counting how many elements you have in each group...

3 answers

2

In this case you can already bring this information from the database, doing a check for each line. Follow an example based on your code:

Query:

SELECT
    os,
    nome,
    data,
    (
        CASE
            WHEN EXISTS(
                SELECT
                    os
                FROM
                    agenda_saidas AS asd
                WHERE
                    id_transfer = 1
                    AND ags.os = asd.os
                    AND ags.id <> asd.id
                LIMIT 1
            ) THEN 1
            ELSE 0
        END
    ) AS duplicado
FROM
    agenda_saidas AS ags
WHERE
    id_transfer = ?;

PHP(if)

if ($row['duplicado']) {
    $corlinha ='red';
} else {
    $corlinha ='white';  
}

Follow a fiddle with example: https://www.db-fiddle.com/f/WoAPxJ6DazzS44hhwHshq/2

  • Ola Didn’t work gave this result ( red red red red red red ) but it would have to be this ( red red white red red red red red ) os 1 , 1 , 2 , 3 , 3

  • @Fabiohenrique really was missing validate if a existed but with a different id (primary key). I changed the example and included a fiddle running the example

1

Create a variable ($anterior) that stores the previous record, and then make the comparison. Remember to update it to the current value at the end of while.

$anterior = array('id' => 0);
while($row = $resultcar->fetch_assoc() ){                              
    if($anterior['id'] == $row['id']){
        $corlinha ='red';
    }else{
        $corlinha ='white';  
    }
    $anterior = $row;
}

1

A very simple routine.

At the end of while assign the value of the variable $os a new variable, for example $oldOs. Once this is done, each iteration will be a comparison of the new value of $os with $oldOs that is to say if($oldOs==$os){

......
$os = $row['os'];
$nome = $row['nome'];
$data = $row['data'];

if($oldOs==$os){
  $corlinha ='red';
}else{
  $corlinha ='white';  
}

$oldOs=$os;
..........

Browser other questions tagged

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