i get this error:
Warning: Attempt to read property "squadra" on array in C:\xampp\htdocs\statistiche-calcio\index.php on line 57
this is the code of my db.php file:
<?php
function connect($dbHost, $dbName, $dbUsername, $dbPassword){
$db = new mysqli(
$dbHost,
$dbUsername,
$dbPassword,
$dbName
);
if($db->connect_error){
die("Impossibile connettersi al database \n" . $db->connect_error . "\n" . $db->connect_errno);
}
return $db;
}
function fetchAll(mysqli $db, $table){
$data = [];
$sql = "SELECT * FROM $table";
$results = $db->query($sql);
if($results->num_rows > 0){
while($row = $results->fetch_object()){
$data[] = $row;
}
}
return $data;
}
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;
}
and this is my index.php where i get the error:
<?php
require_once('config.php');
require_once('db.php');
$db = connect(
DB_HOST,
DB_NAME,
DB_USERNAME,
DB_PASSWORD,
);
$records = [];
$records = fetchAll($db, 'partite');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
table, th, td{
border: 1px solid grey;
text-align: center;
}
</style>
<h1>Risultati Premier League</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Data</th>
<th>Casa</th>
<th>Risultato</th>
<th>Ospite</th>
<th>Risultato 1 tempo</th>
</tr>
</thead>
<tbody>
<?php
if(count($records) > 0):
foreach($records as $record):
$squadra_casa = fetchSquadra($db, 'squadre', $record->squadra_casa);
$squadra_ospite = fetchSquadra($db, 'squadre', $record->squadra_ospite);
?>
<tr>
<td><?php echo $record->id;?></td>
<td><?php echo $record->data;?></td>
<td><?php echo $squadra_casa->squadra;?></td>
<td><?php echo $record->goal_casa . " - ". $record->goal_ospite;?></td>
<td><?php echo $squadra_ospite->squadra;?></td>
<td><?php echo $record->goal_casa_1t . " - ". $record->goal_ospite_1t;?></td>
</tr>
<?php
endforeach;
else: ?>
<tr>
<td colspan="6">Non è stata trovata nessuna partita!</td>
</tr>
<?php endif ?>
</tbody>
</table>
</body>
</html>
I have try to var_dump() the variable $squadra_casa and i get this:
array(1) { [0]=> object(stdClass)#5 (3) { ["id"]=> string(2) "18" ["squadra"]=> string(6) "Fulham" ["campionato"]=> string(1) "1" } }
but when i try to echo out the $squadra_casa->squadra property i get the error.
How can i solve it? What i'm doing wrong?
you should try $squadra_casa[0]->squadra
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With