0
$i=0;
$sql = $dbh->prepare('SELECT kappaleen_nimi, levy_id, kesto FROM kappaleet');
$ok = $sql->execute();
if(!$ok) { print_r( $sql->errorInfo() ) ; }
while($row = $sql->fetch(PDO::FETCH_ASSOC) ) {
foreach($row as $value) {
    if($value!=null || $value!=0){
        $haku2[$i] = $value;
        $i=$i+1;
    }
}
}

I'm working with this sql database, where i'm fetching kappaleen_nimi (name of the track), levy_id (record_id) and kesto (length) from the sql table kappaleet. I'm trying to remove fields containing null or 0. However, the final zero gets through anyway through this filter: "if($value!=null || $value!=0)".

When printing my table the following way:

foreach($haku2 as $value){
    echo $value.', ';
}

I get this kind of result (last few fields): "Sateen tango, 7, 3.11, 0, "

The final zero is still there, and i can't get my head around it, why the he** it passes the if condition... I know that the final zero is levy_id (record_id).

user3629146
  • 107
  • 2
  • 12
  • If you know that levy_id is 0 just filter it in the query `SELECT kappaleen_nimi, levy_id, kesto FROM kappaleet WHERE levy_id !=0` – Mihai Nov 20 '14 at 12:11
  • the type of `$value` will be `string`, not `int`, and because `'0' != null` os true, `'0' != 0` is never evaluated. Quick tip: instead of using that `$i` and `$i = $i +1;` business, adding values to an array is easier done using `$array[] = 'add this';` – Elias Van Ootegem Nov 20 '14 at 12:11
  • @EliasVanOotegem http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_not-equal it is valid,it`s not as widely used as <> – Mihai Nov 20 '14 at 12:15
  • @EliasVanOotegem `!=` is a valid operator... – RichardBernards Nov 20 '14 at 12:16
  • 1
    @Mihai: Nips, so it is... I thought I'd ran into trouble using `!=` somewhere, but I guess I was confused :) – Elias Van Ootegem Nov 20 '14 at 12:20

1 Answers1

1

I think you are looking for an AND conditional instead of an OR. To fix this, replace the following line

if($value!=null || $value!=0){

with this one

if($value!=null && $value!=0){
RichardBernards
  • 3,146
  • 1
  • 22
  • 30
  • When i tried that code, it removes also the kappaleen_nimi from the table, giving this kind of format: 1, 3.42, 1, 2.52, 1, 3.53, etc... – user3629146 Nov 20 '14 at 12:13
  • @user3629146 Add a few rows from your database with the expected result in your question please, than we can provide you with a better answer. – RichardBernards Nov 20 '14 at 12:17