Can you select and update in the same query? I'm trying to count views to create a top blog posts by views for my sidebar.
$sql = mysql_query("SELECT * FROM articles WHERE id='$id' LIMIT 1
UPDATE pages SET views=views+1 WHERE ID=$id");
The query structure, “UPDATE from SELECT” can be used to perform this type of data update scenario. Also, we can use alternative MERGE statements and subquery methods.
User can update the data in one table using data already stored in another table. We will use UPDATE command and SELECT command. After creating two tables, we insert values on each column of two tables after defining its data types. We have use SELECT command and UNION command to put the values of one row together.
Example: SELECT FOR UPDATE in action A complete transaction that uses SELECT FOR UPDATE on that table could look like this: BEGIN; SELECT * FROM kv WHERE k = 1 FOR UPDATE; UPDATE kv SET v = v + 5 WHERE k = 1; COMMIT ; Working line by line through the statement above: The first line, BEGIN , initiates the transaction.
Like SELECT , the UPDATE statement can have a subquery in several places or clauses. In an UPDATE , the two clauses in which subqueries are used most commonly are SET and WHERE . The SET clause is where we define the new value for the column being modified by the UPDATE .
No, you cannot do that, but there is nothing wrong with doing two queries.
mysql_query("UPDATE pages SET views=views+1 WHERE ID=$id");
$sql = mysql_query("SELECT * FROM articles WHERE id=$id");
Also, if id
is the primary key you don't have to do LIMIT 1
here, id
is unique, therefore it will always have only one result matching your condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With