Jump to content

'foreach' Testing For Strlen($Key) Within A 'while'


rsleventhal

Recommended Posts

I'm in a quandry.

 

I have a series of records in a table. I'm allowing NULLs on my varchar columns, because the imported data may not have values for some of them. I need to manipulate each record with the end-goal of creating another query which will be used to insert data into another table.

 

The first table, with the NULLS permitted, is the one I'm currently traversing with a 'while loop':

$sql = "select * from " . DB_TBL;
$result = mysql_query($sql);
while ($data = mysql_fetch_assoc($result)) {
//my foreach loop goes here
}

 

Pretty straightforward so far. So, I thought, was my foreach loop:

 


   foreach ($data as $key => $value) {
       if ((strlen($value) != 0)) {
           echo "key: " . $key . ': =' . $value . '<br />';
       } else {
           echo '<br />';
}
}

 

When I run that, I seem to lose the first column, which is never NULL or strlen=0. It just doesn't display.

 

Should this be done another way? Perhaps getting the numrows first, then doing the foreach, incrementing the row inside a for/next loop?

 

thanks in advance for any productive ideas.

Thanks to all who replied.

 

@berridgeab: yes, all the data is there when I just dump it out like that.

 

@ Jessica: adding trim(), while a good idea and something I've now done, does not affect the output

 

@ManiacDan: I've run the query by hand in shell and all's as expected. The column I'm losing is always the first column and contains only plain text, no HTML.

 

I have a feeling I'm doing something earlier in the code that's affecting the output, so I'll look there and continue debugging. Will post the solution once i find it.

 

Again, my thanks,

-R

There is no "earlier in the code" for this example, you select data and then print it. If you're not showing us your actual code, there's no way we can help you.

 

You say the data is there when you remove the IF check. That implies that your IF check is failing. Inside that IF check, print out "In the if because strlen('{$value}') is zero<br />"; That should work.

 

your thread title says $key, your code says $value. Are you sure you're checking the right variable?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.