0

Here's my code:

$inv = array('field1','field2','field3','field4');
$sql = "select * from table1 where id='1'";
$result = mysql_query($sql);
if(!$result){
    print mysql_error();    
}else{
    while($row = mysql_fetch_array($result)){
        foreach($inv as $i){
            print $row[$i];
        }
    }
}

table1 consist of the following field name: field1, field2, field3, field4, field5, field6, field7
$inv = explode(',',$item) where $item = table2 $row[value] return a string with comma delimited which may consist 'field1,field2,field5' or 'field3,field4,field6'...etc.

How come it only print the value of field1? What's wrong with this code?

    while($row = mysql_fetch_array($result)){
        print $row['field1'];
        print $row['field2'];
        print $row['field3'];
        print $row['field4'];
    }

But if I do this way it will print all the value.

4
  • by the the fields name are dynamic that's why i need it to be like that. Commented Mar 14, 2013 at 3:18
  • 1
    $inv is already an array, why are you exploding it. print $i and see what the results are. I bet not what you think. Commented Mar 14, 2013 at 3:20
  • 1
    @user2138394 I can see from the revisions that you removed the explode line, which is (was?) the critical point others point out. Are you removing it because it isn't in your actually code? Commented Mar 14, 2013 at 3:25
  • thanks for the answer i just found my mistake, it's just a white space that i need to trim down. Thanks! Commented Mar 14, 2013 at 4:04

2 Answers 2

4

You are using explode() on an array. Explode is used to create an array from a string. You do not have to do this, please refer to the manual http://php.net/explode to understand. Change the lines below

$inv = array('field1','field2','field3','field4');
$item = explode(',',$inv);

to

$item = array('field1','field2','field3','field4');
Sign up to request clarification or add additional context in comments.

3 Comments

Right. Unless you $item = 'field1,field2,field3,field4' there is no reason to explode. @user2138394
sorry i forgot to edit the question, $inv = another table $row['value'] that return a comma delimited string.
thanks for the answer i just found my mistake, it's just a white space that i need to trim down. Thanks!
0

Based on your edit I would guess that your field names contain leading spaces. You should check that with a var_dump() of the $i variables and you can solve it by trimming it:

$i = trim($i);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.