Not sure why I'm getting the following error:
Uncaught Error: Object of class stdClass could not be converted to string
I am following the tutorial here:
https://www.youtube.com/watch?v=ZIsdbVOQJNc&t=20s
Around the 6:16 minute mark is where I'm at.
Here is my code:
<?php
$url = "http://localhost/restapi/";
$data_array = array(
'username' => 'jbeasley',
'fullname' => 'John Beasley',
'email' => 'jbeasley@email.com'
);
$data = http_build_query($data_array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
if($e = curl_error($ch)) {
echo $e;
} else {
$decoded = json_decode($resp);
foreach($decoded as $key => $val) {
echo $key . ': ' . $val . '<br>'; // <-- error is pointing here
}
}
curl_close($ch);
?>
The error is pointing at the $val variable in the foreach loop.
The actual API looks like this:
<?php
require_once __DIR__ . '/config.php';
class API {
function Select() {
$db = new Connect;
$users = array();
$data = $db->prepare('SELECT * FROM users');
$data->execute();
while($OutputData = $data->fetch(PDO::FETCH_ASSOC)) {
// $users[$OutputData['username']] = array(
$users[] = array(
'username' => $OutputData['username'],
'fullname' => $OutputData['fullname'],
'email' => $OutputData['email']
);
}
return json_encode($users);
}
}
$API = new API;
header('Content-Type: application/json');
echo $API->Select();
?>
What am I doing wrong and how can I fix it?
Using the suggestion by aynber, I was able to solve the problem by updating the foreach loop to look like this:
foreach($decoded as $key => $val) {
foreach($val as $key2 => $val2) {
echo $key2 . ': ' . $val2 . '<br>';
}
}