PHP升级至5.6后出现Illegal string offset 'id'错误求助
Hey there! Let's break down why this error showed up post-upgrade and walk through how to fix it.
What's Causing This?
PHP 5.3 was pretty forgiving when you accidentally treated strings like arrays. If you tried to access a string with an array-style key (like $string['id']), it would quietly convert the string key to an integer (usually 0) and grab the first character of the string—no error thrown.
Starting in PHP 5.6, this behavior got stricter. Now it throws the Illegal string offset 'id' error because you're trying to use a string key ('id') on a variable that's actually a string, not the associative array you expected. In your code, that means $row is a string instead of the array you need it to be.
Step-by-Step Fixes
1. First, Confirm What $row Actually Is
Let's debug to be 100% sure about $row's type. Add this line right before your foreach loop to print its content and type:
// Add this to check $row's value and type var_dump($row); foreach($db_table_fields as $key => $value) { // ... rest of your code }
Run your app again, and you'll see if $row is a string, empty, or not the array you thought it was.
2. Fix Where $row Comes From
Most likely, $row comes from a database query. Check how you're fetching results:
- If using MySQLi: Make sure you're using
mysqli_fetch_assoc()(returns an associative array) instead ofmysqli_fetch_row()(indexed array) ormysqli_fetch_object()(object). - If using PDO: Ensure you're fetching with
PDO::FETCH_ASSOC(e.g.,$stmt->fetch(PDO::FETCH_ASSOC)) instead of modes that don't return associative arrays.
3. Add Safety Checks to Your Code
Even after fixing the source, adding type checks will prevent this error from popping up again if something goes wrong. Modify your code to validate $row before accessing it:
foreach($db_table_fields as $key => $value) { if($key == 'id') { // Check if $row is an array and the 'id' key exists if(is_array($row) && isset($row[$key])) { $out .= '<td style="display: none;"><input type="'.$value.'" name="'.$key.'[]" value="'.$row[$key].'" /></td>'; } else { // Fallback to an empty value if $row isn't valid $out .= '<td style="display: none;"><input type="'.$value.'" name="'.$key.'[]" value="" /></td>'; } } }
Bonus: Secure Your Output
While we're at it, let's add a security layer to prevent XSS attacks. Escape dynamic values with htmlspecialchars():
if(is_array($row) && isset($row[$key])) { $safe_value = htmlspecialchars($row[$key], ENT_QUOTES); $out .= '<td style="display: none;"><input type="'.$value.'" name="'.$key.'[]" value="'.$safe_value.'" /></td>'; }
内容的提问来源于stack exchange,提问作者Braintosaur

