SQL 用新数据更新整个 table

SQL Update a whole table with new data

我 运行 每 15 分钟查询一次,以从 API 检索新数据并将此数据存储在我的数据库中。

所以我想每隔 15 分钟将新数据存储在 table 中,并删除 table 中的所有旧数据。

我目前使用的是以下方法:

$sql = "DELETE FROM self_user_follower
        INSERT INTO self_user_follower (username, profile_picture, full_name, user_id, last_updated)
        VALUES (:query_username, :query_profile_picture, :query_full_name, :query_user_id, :query_last_updated)";

但它给我以下错误:

Array
(
    [0] => 42000
    [1] => 1064
    [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO self_user_follower (username, profile_picture, full_name, user_id, l' at line 2
)
query_error

这是最好的方法还是有更好更简洁的方法?

如果要将两个 SQL 查询放入一个语句字符串中,则必须

  1. 用分号分隔 (;)
  2. 使用支持多查询的函数mysqli_multi_query

除非您有充分的理由,否则请修改您的代码,使其分别执行每个查询。如果您需要,我的SQL我提供transaction support。*

为什么你需要一个单独的函数的原因很有启发性;如文档中所述:

An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.

*: 实际上,我什至不确定 multi_query 是否会在同一事务中执行两个查询 - 我只是猜测您使用多查询的原因。

多条语句应以分号结束

试试这个

$sql = "DELETE FROM self_user_follower;
        INSERT INTO self_user_follower 
(username, profile_picture, full_name, user_id, last_updated)
        VALUES (:query_username, :query_profile_picture, :query_full_name, :query_user_id, 
  :query_last_updated)";