Home » Php » php – How can I insert this JSON into MySQL

php – How can I insert this JSON into MySQL

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to insert JSON into MySQL, I have one class Database with function dbConnection and one function getDati. How can i make another function that insert array from getDati to MySQL.
This is my code in PHP :

<?php  
    class Database
    {        
        private $db_host;
        private $db_name;
        private $db_username;
        private $db_password;


        public function dbConnection()
        {
            $this->db_host = 'localhost';
            $this->db_name = 'items';
            $this->db_username = 'root';
            $this->db_password = '';
            try {
                $conn = new PDO('mysql:host=' . $this->db_host . ';dbname=' . $this->db_name, $this->db_username, $this->db_password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            } catch (PDOException $e) {
                echo "Connection error " . $e->getMessage();
                exit;
            }
        }
    }

    function getDati()
    {
        $url = 'https://jsonplaceholder.typicode.com/todos/';
        $cURL = curl_init();
        curl_setopt($cURL, CURLOPT_URL, $url);
        curl_setopt($cURL, CURLOPT_HTTPGET, true);
        curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Accept: application/json'
        ));

        $result = curl_exec($cURL);
        curl_close($cURL);

        $all_items = json_decode($result);

        return $all_items;
    }

    function intoDB()
    {
        $all_items = getDati();
        $database = new Database;
        $db = $database->dbConnection();
        $this->conn = $db;//not sure if i need this 
        //.. and now i don't know how to continue
    }

var_dump($all_items );

The function getDati return array with 200 objects. How should the statement sholud look like to insert the array into MySQL?

How to&Answers:

Try the following:

Obviously you’d need to change the name of the table to the correct name, and the column names would also need to be changed, but other than that this should work.

function intoDB()
{
    $all_items = getDati();
    $database = new Database;
    $db = $database->dbConnection();
    $this->conn = $db;//not sure if i need this 
    //.. and now i don't know how to continue

    foreach($all_items as $k => $item) {

        $sql = "INSERT INTO users (id, userId, title, completed) VALUES (?,?,?,?)";
        $stmt = $db->prepare($sql);
        $stmt->execute([$item->id, $item->userId, $item->title, $item->completed]);

    }
}