Php 链接Mysql查询以进行插入
仅当两个条件为真时,我才尝试插入一行。我想在一份声明中这样做。我的桌子看起来像:Php 链接Mysql查询以进行插入,php,mysql,Php,Mysql,仅当两个条件为真时,我才尝试插入一行。我想在一份声明中这样做。我的桌子看起来像: [Table] id, userId, locationId, type, timestamp --------------------------------------- 1 5 19 0 2017-03-28 03:05:48 2 5
[Table]
id, userId, locationId, type, timestamp
---------------------------------------
1 5 19 0 2017-03-28 03:05:48
2 5 19 1 2017-03-29 00:57:57
是否有一种执行sql的方法:
LIRFU=用户的最后插入行=从表中选择*,其中userId=$userId ORDER BY timestamp DESC LIMIT 1
如果LIRFU.type=0,则插入一行$userId、$locationId、1。
如果LIRFU.type=1和LIRFU.locationId!=则插入一行$userId、$locationId、0$locationId。
让我们调用您的表,用户类型
下面的语句用于在LIRFU.type=0时插入包含示例数据5,19,1的行:
您可以通过用?替换数据,将其转换为PHP中的准备语句
如果LIRFU.type=1且LIRFU.locationId!=1,那么下面的语句将插入一行,其中包含示例数据5,19,019:
用PHP编写时也有同样的想法:
$stmt = $db->prepare("INSERT INTO User_Types (userId, locationId, type) SELECT @userId:=?, @locationId:=?, 0 from dual WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 1 AND (SELECT locationId FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) <> @locationId");
$stmt->bind_param('ii', $user_id, $location_id);
//if LIRFU.type = 1 and LIRFU.locationId != $location_id
$stmt->execute();
$stmt = $db->prepare("INSERT INTO User_Types (userId, locationId, type) SELECT @userId:=?, ?, 1 from dual WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 0");
$stmt->bind_param('ii', $user_id, $location_id);
//if LIRFU.type = 0
$stmt->execute();
INSERT INTO User_Types (userId, locationId, type)
SELECT @userId:=5, @locationId:=19, 0 from dual
WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 1
AND (SELECT locationId FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) <> @locationId;
$stmt = $db->prepare("INSERT INTO User_Types (userId, locationId, type) SELECT @userId:=?, @locationId:=?, 0 from dual WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 1 AND (SELECT locationId FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) <> @locationId");
$stmt->bind_param('ii', $user_id, $location_id);
//if LIRFU.type = 1 and LIRFU.locationId != $location_id
$stmt->execute();