Search code examples
phpmysql

Fatal error: [] operator not supported for strings


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?


Solution

  • 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.

    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'];
    

    PHP 7 tightened controls around 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.