简体   繁体   English

重新加载页面PHP时如何检查MySQL表是否为空

[英]How to check if MySQL table is empty or not when I reload page PHP

I work on a CRUD PHP page and everything works perfectly.我在 CRUD PHP 页面上工作,一切正常。 The data that I take is from JSON url ( https://jsonplaceholder.typicode.com/todos/ ).我获取的数据来自 JSON url ( https://jsonplaceholder.typicode.com/todos/ )。

How can I check and populate MySQL table if is empty every time when i load my index page.每次加载索引页面时,如何检查和填充 MySQL 表是否为空。

This my PHP code how I connect to database.这是我的 PHP 代码如何连接到数据库。 And function to inset JSON data to MySQL(I'm not sure that works correctly) :以及将 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;
        }
    }
}

Function getDati() that works correctly and returns array with 200 objects函数getDati()正常工作并返回包含 200 个对象的数组

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.

It should be IF that will check if table is full or empty but I donk know how to do that.应该是IF来检查表是满还是空,但我不知道该怎么做。

When I recall intoDB() nothing happens.当我回忆intoDB()什么也没有发生。 MySQL table remain empty. MySQL 表保持为空。 I want to check every time when I reload or open index page that my MySQL table is populated and if it is empty to populate it.我想在每次重新加载或打开索引页面时检查我的 MySQL 表是否已填充以及是否为空以填充它。 Any suggestion how to do that?任何建议如何做到这一点? Thanks in advance!提前致谢!

When selecting count(*) , one row is returned, which contains the count so the response will be something like ['count(*)' => 0].选择count(*) ,将返回一行,其中包含计数,因此响应将类似于 ['count(*)' => 0]。

$number_of_rows = $result->fetchColumn(); // This contains 1 row, with the column indicating the count and so your condition will never be executed

Rather alias the column SELECT count(*) as total_posts FROM posts而是将列SELECT count(*) as total_posts FROM posts别名SELECT count(*) as total_posts FROM posts

$row = $stmt->fetch(PDO::FETCH_ASSOC); // Fetch the first row
$total_posts = $row['total_posts']; // Get the column containing the result of the count
// Run your condition $total_posts 

Checkout this answer签出这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM