Illegal string offset error when trying to display a multidimensional query

Hi, just to make it clear, I am a newbie with php and sql. Started with it 6 months ago.

I want to display each songname and the multiple genres that it is combined of. That is a many to many relation.

Quick norwegian vocabulary:
sjanger = genre
navn = name
sang = song
godkjenning = verification

Here is my code:

$sql = "SELECT sa.*, sj.sjangernavn, sj.sjangerid
FROM sjanger AS sj, sang AS sa, sang_has_sjanger AS ss, godkjenning 
WHERE godkjenning.godkjenningid = 3
		AND godkjenning.godkjenningid = sa.fragodkjenning
		AND sj.sjangerid = ss.sjanger_sjangerid
        AND sa.sangid = ss.sang_sangid";
   
$datasett		=	mysqli_query($tilkobling, $sql);

				while ($rad = mysqli_fetch_array($datasett))
				{
					
                    $sanger[ $rad[ 'sangid' ] ][ 'sangnavn' ] = $rad[ 'sangnavn' ];

                    $sanger[ $rad[ 'sangid' ] ][ 'sjangernavn' ][ $rad[ 'sjangerid' ] ] = $rad[ 'sjangernavn' ]; 
                      
				};


foreach ( $sanger as $sangid => $sang ) { 

    echo $sang['sangnavn'];

    foreach ( $sang[ 'sjangernavn' ] as $sjangerid => $sjangernavn ) { 

      echo $sjangernavn['sjangernavn'];    
              
    }

}    
   

line
When I run this I get:

This is the query testing output

Without “echo $sjangernavn[‘sjangernavn’];” which is the line 28, I get:
screen 3

Hi @theostene2 and a warm welcome to the SP Forums.

Try adding this debug function to display the values type and content:

echo ‘<pre>’; var_dump($variable_name); die;

Edit and explanation:

  1. <pre> // adds linefeeds to make arrays and objects easier to read
  2. var_dump(…); // displays variable content
  3. die; // halts program execution

Edit:

Try this:
echo $sang[$sangnavn]:

Instead of this:

echo $sang[‘sangnavn’];

Hi, the echo $sang[$sangnavn]: didn’t work.

the echo ‘<pre>’; var_dump($variable_name); die; also didn’t work, but if I instead wrote echo '<pre>'; print_r($sanger); echo '</pre>'; then I get this:

1 Like

YESSS I got it to work. just had to echo $sjangernavn; instead of echo $sjangernavn ['sjangernavn'];

1 Like