我在一个CRUD PHP页面上工作,一切都很完美。我获取的数据来自JSON url(
https://jsonplaceholder.typicode.com/todos/
如果每次加载索引页时都是空的,我如何检查并填充MySQL表。
这是我连接数据库的PHP代码。函数将JSON数据插入MySQL(我不确定是否正确):
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;
}
}
}
功能
getDati()
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()
{
$database = new Database;
$db = $database->dbConnection();
$all_items = getDati();
$sql = "SELECT count(*) FROM posts ";
$result = $db->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
if ($number_of_rows <= 0) {
foreach ($all_items as $k => $item) {
$sql = "INSERT INTO posts (id, userId, title, completed) VALUES (?,?,?,?)";
$stmt = $db->prepare($sql);
$stmt->execute([$item->id, $item->userId, $item->title, $item->completed]);
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documents</title>
<link rel="stylesheet" href="./style.css">
<script src="https://kit.fontawesome.com/12883fd222.js" crossorigin="anonymous"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<?php
require_once 'process.php';
intoDB(); // this is where i call the function.
应该是
IF
这将检查表是满的还是空的,但我不知道怎么做。
intoDB()
什么都没发生。MySQL表保持为空。每次重新加载或打开索引页时,我都要检查MySQL表是否已填充,以及填充该表是否为空。有什么建议吗?提前谢谢!