Hi! Could we please enable some services and cookies to improve your experience and our website?

PHPize Online / SQLize Online  /  SQLtest Online

A A A
Login    Share code      Blog   FAQ

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

Copy Format Clear
CREATE TABLE IF NOT EXISTS products ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255), brand VARCHAR(255), category VARCHAR(255), thumbnail TEXT, price DECIMAL(10,2) );

Stuck with a problem? Got Error? Ask AI support!

Copy Clear
Copy Format Clear
<?php $resource = 'products'; $category = 'smartphones'; $needle = 'iPhone'; $url = 'https://dummyjson.com/'; function fetchDataByCategory(string $url, string $resource, string $category): array { $url = $url . $resource . '/category/' . $category; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); if (!$response) die("Ошибка загрузки '{$resource}'"); return json_decode($response, true)[$resource]; } function filterData(array $data, string $needle): array { $items = []; foreach($data as $item) { if (stripos($item['title'], $needle) !== false) { array_push($items, $item); } } return $items; } function insertItemToDb($item, $category) { global $pdo; $sql = "INSERT INTO {$category} (title, description, brand, category, thumbnail, price) VALUES (:title, :description, :brand, :category, :thumbnail, :price)"; var_dump($sql); try { $stmt = $pdo->prepare($sql); $stmt->execute([ ":title" => $item['title'], ":description" => $item['description'], ":brand" => $item['brand'], ":category" => $item['category'], ":thumbnail" => $item['thumbnail'], ":price" => $item['price'] ]); } catch (PDOException $e) { echo "Ошибка при сохранении {$category}: " . $e->getMessage() . "\n"; } } $data = fetchDataByCategory($url, $resource, $category); $filteredData = filterData($data, $needle); foreach ($filteredData as $item) { insertItemToDb($item, $category); }
Copy Clear