[英]How to make my php code faster?
I'am using php on server side to manage data with MySQL. 我在服务器端使用php通过MySQL管理数据。 I have to request a API that gives me an list of users.
我必须请求一个给我用户列表的API。 I need to check for each user if he is in the database.
我需要检查每个用户是否在数据库中。 If yes, I update his information.
如果是,我将更新他的信息。 If not, I insert him in the data base.
如果没有,我将他插入数据库中。
The issue is that there is more than 2000+ users each times and my code in PHP is really slow (sometimes I get 504 Gateway Time-out). 问题是每次有2000多个用户,而我在PHP中的代码确实很慢(有时我收到504网关超时)。 We will have even more users very soon.
我们很快就会有更多的用户。
How can I make my code faster ? 如何使我的代码更快? Is Php ok ?
可以吗?
EDIT my codeV3 after improvement: 改进后编辑我的codeV3:
$userList = getFromAPI();
foreach ($userList as $userId){
$db = dbConnect();
$tagList = implode(",", $user["tagid_list"]);
$query = $db->prepare(
"INSERT INTO USERS(id, name, group) VALUES(:id, :name, :group)
ON DUPLICATE KEY UPDATE name=values(name), group=values(group)"
);
$query->execute([
"id"=>$id,
"name"=>$name,
"group"=>$group
]);
}
Maybe try with putting $db = dbConnect();
也许尝试用
$db = dbConnect();
outside of your foreach? 在你的foreach之外? I don't know if it is needed to open the connection in each cycle.
我不知道是否需要在每个周期中打开连接。 It may be time consuming aswell.
这也可能很耗时。
You can use a single query for that: 您可以为此使用单个查询:
INSERT INTO users (id, name)
VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Cecil')
ON DUPLICATE KEY UPDATE name = VALUES(name);
In a nutshell: you insert new rows, but if one already exists (the key is duplicated), it is updated instead. 简而言之:您插入新行,但是如果已经存在(键重复),则会更新它。 You can build your insert values in a loop so you end up with a single query instead of 4000+.
您可以在循环中构建插入值,因此最终将得到一个查询,而不是4000+。
First of all get fetching all users ids from database out of foreach lopp and buffer it in some variable. 首先,从foreach lopp中获取数据库中的所有用户ID,并将其缓冲在某个变量中。 Should be better.
应该更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.