Attempt to read property on array: Why Your Data Isn't What You Think It Is
The error message Warning: Attempt to read property "squadra" on array is a classic PHP trap that stems from a mismatch between how you expect data to be structured and how it actually is returned from your helper functions. In the code snippet provided, you are treating $squadra_casa as an object with properties like ->squadra, but PHP is telling you that this variable is currently an array.
This discrepancy usually points to a specific issue in the logic of your fetchSquadra function. Looking at your implementation:
function fetchSquadra(mysqli $db, $table, $squadra){
$data = [];
$sql = "SELECT * FROM $table WHERE id = " . $squadra;
$results = $db->query($sql);
if($results->num_rows === 1){
while($row = $results->fetch_object()){
$data[] = $row;
}
}
return $data;
}
The core problem lies in the return statement. Regardless of whether a row is found or not, the function always returns $data, which is initialized as an empty array ([]) at the very beginning. Even though you have a conditional block that appends objects to $data only if exactly one row exists, the variable itself remains an array container.
When you iterate through the matches in index.php and call fetchSquadra, the function returns an array (e.g., Array ( [0] => stdClass Object (...))). Consequently, when you attempt to access $squadra_casa->squadra, PHP tries to read a property off an array, triggering the warning.
To fix this, you need to return the object directly if it exists, rather than wrapping it in an array. If you anticipate that your query might return zero rows, you should handle that case explicitly to avoid returning a potentially confusing empty array or null. Here is a corrected version of the function:
function fetchSquadra(mysqli $db, $table, $squadra){
// Note: Using prepared statements here would be critical for production to prevent SQL injection
$sql = "SELECT * FROM $table WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i", $squadra); // Assuming ID is an integer
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_object()) {
return $row; // Return the object directly
}
return null; // Or handle the "not found" case gracefully
}
With this change, $squadra_casa will be either an stdClass object (if the team exists) or null. You must then update your index.php logic to check for null before trying to access properties:
$squadra_casa = fetchSquadra($db, 'squadre', $record->squadra_casa);
// Check if the team was found before accessing properties
if ($squadra_casa === null) {
// Handle missing data, e.g., show a placeholder or skip the row
continue;
}
echo $squadra_casa->squadra;
Security Warning: SQL Injection Vulnerability
Beyond the immediate bug fix, there is a significant security vulnerability in your current code. You are constructing SQL queries by directly concatenating user-controlled variables (like $squadra) into the string before execution. This leaves your application open to SQL injection attacks.
An attacker could manipulate the $squadra input to alter the query logic or access unauthorized data. For instance, passing 1 OR 1=1-- would bypass the WHERE id = ... clause and return every row from the table. Always use prepared statements with bound parameters, as demonstrated in the refactored function above.
Alternative Approaches
If you prefer to keep using arrays instead of objects throughout your application, you can adjust your helper functions to return associative arrays:
function fetchSquadra(...$args) {
// ... query logic ...
$data = [];
if($results->num_rows === 1){
while($row = $results->fetch_assoc()){ // Use fetch_assoc instead of fetch_object
$data[] = $row;
}
}
return $data[0] ?? null;
}
In this scenario, $squadra_casa would be an array, and you would access the name using $squadra_casa['squadra']. While objects are often more convenient for single-row lookups, arrays can simplify iteration if you are fetching large datasets. The choice depends on whether you prioritize ease of property access (objects) or memory efficiency and flexibility (arrays).
Conclusion
The error arises because your helper function returns an array wrapper instead of the object itself. By refactoring fetchSquadra to return the object directly and adding a null check in your view layer, you resolve the immediate warning. Simultaneously, migrating to prepared statements ensures your database interactions remain secure against injection attacks.
