Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fatal error: [] operator not supported for strings

Tags:

php

mysql

I'm getting information from database, saving it in array and echoing it in a form with loop structure and I'm having problems when I try to save the modified information to database.

I'm getting this error:

Fatal error: [] operator not supported for strings in....

Code:

$namesql1 = "SELECT name,date,text,date2 FROM table WHERE something= '$something'"; $nameresult1 = mysql_query($namesql1); $countrows = mysql_num_rows($nameresult1); while ($row = mysql_fetch_array($nameresult1, MYSQL_ASSOC)) {     $name[] = $row['name'];     $date[] = $row['date'];     $text[] = $row['text'];     $date2[] = $row['date2 ']; }  /** SOME CODE HERE **/       $wrotesql = "UPDATE service_report SET  name ='$name' , $date = '$date',$text = '$text[$nro]', ser_date = '$date2[$nro]' WHERE something = '$something')";  $wroteresult = mysql_query($wrotesql); 

Could somebody please give me a hint what I'm doing wrong?

like image 986
Henkka Avatar asked May 04 '11 07:05

Henkka


2 Answers

You get this error when attempting to use the short array push syntax on a string.

For example, this

$foo = 'foo'; $foo[] = 'bar'; // ERROR! 

I'd hazard a guess that one or more of your $name, $date, $text or $date2 variables has been initialised as a string.

Edit: Looking again at your question, it looks like you don't actually want to use them as arrays as you're treating them as strings further down.

If so, change your assignments to

$name = $row['name']; $date = $row['date']; $text = $row['text']; $date2 = $row['date2']; 

It seems there are some issues with PHP 7 and code using the empty-index array push syntax.

To make it clear, these work fine in PHP 7+

$previouslyUndeclaredVariableName[] = 'value'; // creates an array and adds one entry  $emptyArray = []; // creates an array $emptyArray[] = 'value'; // pushes in an entry 

What does not work is attempting to use empty-index push on any variable declared as a string, number, object, etc, ie

$declaredAsString = ''; $declaredAsString[] = 'value';  $declaredAsNumber = 1; $declaredAsNumber[] = 'value';  $declaredAsObject = new stdclass(); $declaredAsObject[] = 'value'; 

All result in a fatal error.

like image 140
Phil Avatar answered Sep 20 '22 00:09

Phil


You have probably defined $name, $date, $text or $date2 to be a string, like:

$name = 'String'; 

Then if you treat it like an array it will give that fatal error:

$name[] = 'new value'; // fatal error 

To solve your problem just add the following code at the beginning of the loop:

$name = array(); $date = array(); $text = array(); $date2 = array(); 

This will reset their value to array and then you'll able to use them as arrays.

like image 34
Shoe Avatar answered Sep 23 '22 00:09

Shoe