4

my problem is with rows mysql_query. I need:

Record 0: 2,text is text,3.23

But I have:

Record 0: 2
Record 1: text
Record 2: is
Record 3: text
Record 4: 3.23

Please help me.

results=($(mysql --user root -proot test -Bse "select id,name from Object"));

cnt=${#results[@]}

for (( i=0 ; i<${cnt} ; i++ ))
do
    echo "Record No. $i: ${results[$i]}"

    fieldA=${results[0]};
    fieldB=${results[1]};

done
1
  • I don't understand why you're assigning fieldA and fieldB inside the for loop; if you want those to contain certain parts of each record, you shouldn't assign whole records to them. Commented Feb 18, 2013 at 9:04

1 Answer 1

6

The problem is that you are storing the output of mysql into an array. Now, if mysql returns multiple records you won't know when a record ends and the next one starts because the array will contain the "flattened" data e.g. ( record1_fieldA record1_fieldB record2_fieldA record2_fieldB ... )

Instead, use a while loop to iterate over the records like this:

i=0
while read fieldA fieldB
do
    echo "Record $(( i++ )): fieldA: $fieldA fieldB: $fieldB"
done < <(mysql --user root -proot test -Bse "select id,name from Object")
Sign up to request clarification or add additional context in comments.

3 Comments

but, what when any field is empty? I have: ('aaao-230-27910', 1, 101, '0', '18435', ,); I want: ('','aaao-230-27910', 1, 101, '0', '18435');
I use it: while read fieldA fieldB fieldC fieldD fieldE fieldF fieldG fieldH fieldI fieldJ$ ... do echo "$INS1 $fieldA, '$fieldB', '$fieldC', $fieldD, $fieldE, $fieldF, $field$ ... done < <(mysql --user root -pnorbert test -Bse "select id, name, description, ....
And I have problem in Last field. I have two field in one (0 and 23654): ...1, 101, 0 23654);

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.