Deimos
Deimos

Reputation: 269

SELECT AND THEN UPDATE COUNT number mysqli

I'm trying to get all the rows from my table products, and then update the product_views too, at the same time,

SELECT * FROM `product` WHERE `id` = '26' AND `product_enable`= '1' AND UPDATE `product` SET `product_views` = product_views+1;

This code doesn't work, but i think can help for explain what i want to do,... Is there a good way to do this, I think with making this in 1 query should be good for the system right?

So, thanks for you help

Upvotes: 2

Views: 1532

Answers (2)

Aziz Saleh
Aziz Saleh

Reputation: 2707

Use mysqli multi query: http://www.php.net/manual/en/mysqli.multi-query.php

$sql = "SELECT * FROM `product` WHERE `id` = '26' AND `product_enable`= '1'; ";
$sql.= "UPDATE `product` SET `product_views` = product_views+1;";

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result());

Update 2:

It is possible, check out: http://php.net/manual/en/mysqli.quickstart.multiple-statement.php

Probably the error occurs because the last ; was missing (added it in).

Upvotes: 2

Loïc
Loïc

Reputation: 11942

You just did it the wrong way :

UPDATE `product` SET `product_views` = 
     (SELECT product_views FROM `product` WHERE `id` = '26' AND `product_enable`= '1')+1;

Upvotes: 4

Related Questions