Php, ошибка при сохранении в базу данных

возникает ошибка при записи в базу данных

Warning: Array to string conversion in C:\OSPanel\home\php-rest-api\public\index.php on line 17

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\OSPanel\home\php-rest-api\public\index.php:17 Stack trace: #0 C:\OSPanel\home\php-rest-api\public\index.php(17): PDOStatement->execute(Array) #1 C:\OSPanel\home\php-rest-api\public\index.php(70): Db->create() #2 C:\OSPanel\home\php-rest-api\public\index.php(76): Rest->createdata() #3 {main} thrown in C:\OSPanel\home\php-rest-api\public\index.php on line 17

Сам код:

<?
require __DIR__ . '/../core/connect.php';

class Db
{
    public $data = [];
    public function __construct($data)
    {
        $this->data[]= $data;
    }

    public function create()
    {
        global $pdo;
        $sql = "INSERT INTO `data2` (`name`, `street`, `city`) VALUES (?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$this->data]);
    }
}

class Rest
{
    public static function dump($ar)
    {
        echo '<pre>';
        print_r($ar);
        echo '</pre>';
    }
    public function getapi()
    {

        $resp = json_decode(file_get_contents('https://jsonplaceholder.typicode.com/users'), true);

        // $resp = Http::get('https://jsonplaceholder.typicode.com/users');
        // $resp = $resp->json();
        // $this->dump($resp);
        // foreach ($resp as $respublics) {
        //     $names = [];
        //     $this->dump($respublics);
        //     $names[] = $respublics->name;
        //     // return $respublic['name'];
        //     // dd($resp);
        //     // foreach ($respublics as $respublic) {
        //     //     dd($respublic->id);
        //     // }
        //     return $names;
        // }

        // $this->rest = $resp;
        // return $this->rest;
        return $resp;
    }

    public function handleArray($ar)
    {
        $data = [];
        foreach ($ar as $el) {
            $datajson = [
                'name' => $el['name'],
                'street' => $el['address']['street'],
                'city' => $el['address']['city'],
            ];
            $data[] = $datajson;
        }
        return $data;
    }

    public function createdata(){
        $cr = new Db($this->handleArray($this->getapi()));
        $cr->create();
    }
}
$rest = new Rest(); // создали обьект класа
$r = $rest->getapi(); // получили данные api
$rest->dump($rest->handleArray($r)); // распечатали
$rest->createdata();

Ответы (1 шт):

Автор решения: Алексей

Мое решение такое, сделал все в одном классе и это работает:

<?
require __DIR__ . '/../core/connect.php';
require __DIR__ . '/../vendor/autoload.php';

class Rest
{
    public function getapi()
    {

        $resp = json_decode(file_get_contents(
            'https://jsonplaceholder.typicode.com/users'), true);

        // $resp = Http::get('https://jsonplaceholder.typicode.com/users');
        // $resp = $resp->json();
        return $resp;
    }

    public function handleArray($ar)
    {
        $data = [];
        foreach ($ar as $el) {
            $datajson = [
                'name' => $el['name'],
                'street' => $el['address']['street'],
                'city' => $el['address']['city'],
            ];
            $data[] = $datajson;
        }
        return $data;
    }

    public function createdata($arr)
    {
        global $pdo;
        foreach ($arr as $el) {
            $sql = "INSERT INTO `data2` (`name`, `street`, `city`) 
                    VALUES (?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$el['name'], $el['street'], $el['city']]);
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $rest = new Rest();
    // dump($data[0]['name']);
    $rest->createdata($data);
}

// ==oop===================oop====================oop======================

// $resp = json_decode(
       file_get_contents('https://jsonplaceholder.typicode.com/users'),  true);
// dump($resp);
// ===================================================================
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <style>
        .a {
            padding: 10px 30px;
            background-color: blue;
            margin-bottom: 50px;
            color: aliceblue;
            display: inline-flex;
        }
    </style>
    <h1>новый массив для базы</h1>
    <a class="a" href="/">main</a>
    <form action="" method="post">
        <button type="submit">send</button>
    </form>

</body>

</html>
→ Ссылка