How can I check for equal variables within a while

0

How can I check for equal variables within a while?

  • Type if there are lines as the same CODE do something ...

Low I 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 down

    
asked by anonymous 04.09.2017 / 17:06

3 answers

2

In this case you can already bring this information from the database, doing a check for each line. Here's 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';  
}

Here's a fiddle with the example: link

    
04.09.2017 / 17:11
1

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

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

A very simple routine.

At the end of the while, assign the value of the variable $os to a new variable, for example $oldOs . After this iteration, there will be a comparison of the new value of $os with $oldOs or if($oldOs==$os){

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

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

$oldOs=$os;
..........
    
04.09.2017 / 18:54