Reputation: 1382
I don't know what's wrong with my query, this subquery works fine when using select but when update it's not working, how do i make a subquery for the update query?
$query = "UPDATE `product`
SET `default` = '0'
WHERE `product_name` = (
SELECT `product_name`
FROM `product`
WHERE `product_id` = {$_GET['bag']}
) AND `product_id` != {$_GET['bag']};
";
$result = mysqli_query($connection, $query);
Upvotes: 0
Views: 132
Reputation: 8583
@Barmar beat me to it but here was my answer.
UPDATE `product`
INNER JOIN `product` AS `p` ON `p`.`product_name` = `product`.`product_name` AND `p`.`product_id` = {$_GET['bag']}
SET `default` = '0'
WHERE `product`.`product_id` != {$_GET['bag']};
Upvotes: 0
Reputation: 780889
MySQL doesn't allow you to refer to the same table you're updating in a subquery. You have to use a JOIN
.
UPDATE product AS p1
JOIN product AS p2 ON p1.product_name = p2.product_name
SET default = '0'
WHERE p2.product_id = {$_GET['bag']}
AND p1.product_id != {$_GET['bag']}
BTW, you should also learn to use prepared queries instead of variable substitution, to prevent SQL injection.
Upvotes: 1