How to make MySQL value Increase by one, using PHP - php

I have the following database table.
id article_content article_views
1 content.. 48
I am trying to increase the value of the column article_views using mysql query.
I know I can fetch the number and then add +1 and then update the value, but is there any better way to do this?
Thanks :)

Your query becomes -
Update TABLE_NAME SET article_views = article_views+1 WHERE id = 'your_id'

Related

mysql shrink where clause

I have a table with 10 columns and 24 rows that can store a value or can be = 0. They are called msg1, msg2... up to msg10.
I am writing a query to update this table with 0 instead of a specific value in any of the fields.
So I wrote (59 is a test value and will be dinamically updated by php):
UPDATE schedule SET msg1='0' WHERE msg1='59' OR SET msg2='0' WHERE msg2='59'....
OR SET msg10='0' WHERE msg10='59'
This is obviously not working and anyway would be one of the less efficient query I have ever seen. So the question is: what is a clever way of iterating through all the rows and the columns, look for the specific value (i.e. 59) and if yes change it to 0?
I know that i can do it using a for loop but this will end up doing each time 24 query... not efficient too!
You're going to have to reference each column. I'd just do a full scan of the table, and update every row. An index isn't going to help, no need for a WHERE clause. Assuming those columns are character, use single quotes around the values. If those are numeric, you can omit the single quotes.
UPDATE schedule
SET msg1 = IF(msg1='59','0',msg1)
, msg2 = IF(msg2='59','0',msg2)
, msg3 = IF(msg3='59','0',msg3)
, ...
If you want to add a WHERE clause (which isn't really needed), you'd add it after the SET clause...
WHERE msg1='59'
OR msg2='59'
OR msg3='59'
I'd be tempted to write the statement so I only had to specify the value '59' and '0' just one time, like this:
UPDATE schedule s
CROSS
JOIN (SELECT '59' AS oldval, '0' AS newval) v
SET s.msg1 = IF(s.msg1=v.oldval,v.newval,s.msg1)
, s.msg2 = IF(s.msg2=v.oldval,v.newval,s.msg2)
, s.msg3 = IF(s.msg3=v.oldval,v.newval,s.msg3)

Incrementing a field in a database

I've never had or attempted to do this before, but what I want to do is instead of getting the value out of the database and adding 1 to it just to do an update query is just do one UPDATE query and incrementing the field...
Is there a way of using a JOIN query to get the current value and then updating it again with the new one?
As it's literally just incrementing an INT number I thought there may be way around it.
update table_name set field_name=field_name + 1 where <condition>;
You could just do the following:
UPDATE table_name set field_to_increment = field_to_increment + 1 WHERE <cond>
Use this:
UPDATE yourtable SET yourcolumn = yourcolumn+1 WHERE yourid=123;
It's easy to increment a value in a cell:
UPDATE table SET column = column + 1 WHERE id = 123;

MySQL: Adding figures during UPDATE

I'm trying to UPDATE a column for a user, so that they can only ADD a value to the existing value. So for example, if the table looked like this:
UserID 3
Total 12
User adds 4, so it's changed to:
UserID 3
Total 16
I could obviously do this by doing a query, getting the column value, adding it to the new value, and then updating that column... but I was wondering if there was a way to do it without using a SELECT statement first. Perhaps something using SUM()?
So the query might go:
UPDATE Users SET Total=SUM(Total + :total) WHERE UserID = :userID;
If so, what's the correct syntax?
Thanks!
It's as simple as:
UPDATE Users SET Total = Total + :total WHERE UserID = :userID;
You don't need the SUM() since you are just adding the values, SUM() adds the values of a column together.
UPDATE Users
SET Total= Total + :total
WHERE UserID = :userID;

How get incremented value from table

I need to get next id from table (auto_increment).
I could just use SELECT * from table ORDER BY id DESC LIMIT 1;
For example I get 50. But if we delete from table two items I will get 48 but correct one
will be 51. How get correct value even we something delete from table ?
You can only use SHOW TABLE STATUS LIKE 'tablename' to fetch the auto_increment value. A simpler solution might be: SELECT MAX(id) + 1 FROM table, but this is buggy if the last entry was deleted.
show table status like 'table_name'
next id value is in 'Auto_increment' field
SHOW TABLE STATUS LIKE 'table'
The value you want is in the Auto_increment field.
Be careful about concurrency though: by the time you get around to using this value, some other client could have inserted into the table and thus your value is out of date. It's usually best to try to not need this.
SELECT LAST_INSERT_ID() + 1;
gets the last ID used in an insert in an autoincrement column + 1
I see two solutions for the next ID:
1) Select bigger value of a column with max function. Example: select max( id ) from table;
2) Using the command SHOW STATUS LIKE and get the correct index of array. Take a look: http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html
Seems to me you're creating a race condition here.
Why exactly can you not insert the row you want to insert and then use LAST_INSERT_ID() to find it's ID?

How to get ID of the last updated row in MySQL?

How do I get the ID of the last updated row in MySQL using PHP?
I've found an answer to this problem :)
SET #update_id := 0;
UPDATE some_table SET column_name = 'value', id = (SELECT #update_id := id)
WHERE some_other_column = 'blah' LIMIT 1;
SELECT #update_id;
EDIT by aefxx
This technique can be further expanded to retrieve the ID of every row affected by an update statement:
SET #uids := null;
UPDATE footable
SET foo = 'bar'
WHERE fooid > 5
AND ( SELECT #uids := CONCAT_WS(',', fooid, #uids) );
SELECT #uids;
This will return a string with all the IDs concatenated by a comma.
Hm, I am surprised that among the answers I do not see the easiest solution.
Suppose, item_id is an integer identity column in items table and you update rows with the following statement:
UPDATE items
SET qwe = 'qwe'
WHERE asd = 'asd';
Then, to know the latest affected row right after the statement, you should slightly update the statement into the following:
UPDATE items
SET qwe = 'qwe',
item_id=LAST_INSERT_ID(item_id)
WHERE asd = 'asd';
SELECT LAST_INSERT_ID();
If you need to update only really changed row, you would need to add a conditional update of the item_id through the LAST_INSERT_ID checking if the data is going to change in the row.
This is officially simple but remarkably counter-intuitive. If you're doing:
update users set status = 'processing' where status = 'pending'
limit 1
Change it to this:
update users set status = 'processing' where status = 'pending'
and last_insert_id(user_id)
limit 1
The addition of last_insert_id(user_id) in the where clause is telling MySQL to set its internal variable to the ID of the found row. When you pass a value to last_insert_id(expr) like this, it ends up returning that value, which in the case of IDs like here is always a positive integer and therefore always evaluates to true, never interfering with the where clause. This only works if some row was actually found, so remember to check affected rows. You can then get the ID in multiple ways.
MySQL last_insert_id()
You can generate sequences without calling LAST_INSERT_ID(), but the
utility of using the function this way is that the ID value is
maintained in the server as the last automatically generated value. It
is multi-user safe because multiple clients can issue the UPDATE
statement and get their own sequence value with the SELECT statement
(or mysql_insert_id()), without affecting or being affected by other
clients that generate their own sequence values.
MySQL mysql_insert_id()
Returns the value generated for an AUTO_INCREMENT column by the
previous INSERT or UPDATE statement. Use this function after you have
performed an INSERT statement into a table that contains an
AUTO_INCREMENT field, or have used INSERT or UPDATE to set a column
value with LAST_INSERT_ID(expr).
The reason for the differences between LAST_INSERT_ID() and
mysql_insert_id() is that LAST_INSERT_ID() is made easy to use in
scripts while mysql_insert_id() tries to provide more exact
information about what happens to the AUTO_INCREMENT column.
PHP mysqli_insert_id()
Performing an INSERT or UPDATE statement using the LAST_INSERT_ID()
function will also modify the value returned by the mysqli_insert_id()
function.
Putting it all together:
$affected_rows = DB::getAffectedRows("
update users set status = 'processing'
where status = 'pending' and last_insert_id(user_id)
limit 1"
);
if ($affected_rows) {
$user_id = DB::getInsertId();
}
(FYI that DB class is here.)
This is the same method as Salman A's answer, but here's the code you actually need to do it.
First, edit your table so that it will automatically keep track of whenever a row is modified. Remove the last line if you only want to know when a row was initially inserted.
ALTER TABLE mytable
ADD lastmodified TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
Then, to find out the last updated row, you can use this code.
SELECT id FROM mytable ORDER BY lastmodified DESC LIMIT 1;
This code is all lifted from MySQL vs PostgreSQL: Adding a 'Last Modified Time' Column to a Table and MySQL Manual: Sorting Rows. I just assembled it.
Query :
$sqlQuery = "UPDATE
update_table
SET
set_name = 'value'
WHERE
where_name = 'name'
LIMIT 1;";
PHP function:
function updateAndGetId($sqlQuery)
{
mysql_query(str_replace("SET", "SET id = LAST_INSERT_ID(id),", $sqlQuery));
return mysql_insert_id();
}
It's work for me ;)
SET #uids := "";
UPDATE myf___ingtable
SET id = id
WHERE id < 5
AND ( SELECT #uids := CONCAT_WS(',', CAST(id AS CHAR CHARACTER SET utf8), #uids) );
SELECT #uids;
I had to CAST the id (dunno why)... or I cannot get the #uids content (it was a blob)
Btw many thanks for Pomyk answer!
Hey, I just needed such a trick - I solved it in a different way, maybe it'll work for you. Note this is not a scalable solution and will be very bad for large data sets.
Split your query into two parts -
first, select the ids of the rows you want to update and store them in a temporary table.
secondly, do the original update with the condition in the update statement changed to where id in temp_table.
And to ensure concurrency, you need to lock the table before this two steps and then release the lock at the end.
Again, this works for me, for a query which ends with limit 1, so I don't even use a temp table, but instead simply a variable to store the result of the first select.
I prefer this method since I know I will always update only one row, and the code is straightforward.
ID of the last updated row is the same ID that you use in the 'updateQuery' to found & update that row. So, just save(call) that ID on anyway you want.
last_insert_id() depends of the AUTO_INCREMENT, but the last updated ID not.
My solution is , first decide the "id" ( #uids ) with select command and after update this id with #uids .
SET #uids := (SELECT id FROM table WHERE some = 0 LIMIT 1);
UPDATE table SET col = 1 WHERE id = #uids;SELECT #uids;
it worked on my project.
Further more to the Above Accepted Answer
For those who were wondering about := & =
Significant difference between := and =, and that is that := works as a variable-assignment operator everywhere, while = only works that way in SET statements, and is a comparison operator everywhere else.
So SELECT #var = 1 + 1; will leave #var unchanged and return a boolean (1 or 0 depending on the current value of #var), while SELECT #var := 1 + 1; will change #var to 2, and return 2.
[Source]
If you are only doing insertions, and want one from the same session, do as per peirix's answer. If you are doing modifications, you will need to modify your database schema to store which entry was most recently updated.
If you want the id from the last modification, which may have been from a different session (i.e. not the one that was just done by the PHP code running at present, but one done in response to a different request), you can add a TIMESTAMP column to your table called last_modified (see http://dev.mysql.com/doc/refman/5.1/en/datetime.html for information), and then when you update, set last_modified=CURRENT_TIME.
Having set this, you can then use a query like:
SELECT id FROM table ORDER BY last_modified DESC LIMIT 1;
to get the most recently modified row.
No need for so long Mysql code. In PHP, query should look something like this:
$updateQuery = mysql_query("UPDATE table_name SET row='value' WHERE id='$id'") or die ('Error');
$lastUpdatedId = mysql_insert_id();

Categories