1

I have a integer column in a MySQL table called col1. Now, what I need is to increase its value by some number say 1 (maybe 2, 3 or anything). i.e. If it was already holding value of 10, now I want it to become 11. I know, I can do it by first selecting the original value, increment it with PHP and then update the value. But I wanted to know if there is a way through which I don't have to select the previous value to increment it.

4 Answers 4

6

This can be done very simply, just execute a query like this

$sql = "UPDATE tablename SET col1=col1+1 WHERE key=99";

Or any value you like

$sql = "UPDATE tablename SET col1=col1+3 WHERE key=99";
Sign up to request clarification or add additional context in comments.

Comments

1

I have a table with a single record used for multiple counters.

  1. Manually create a table called counts with a single Int column, named myCount.
    (Later, add more Int columns for additional counters.)
    ie., CREATE TABLE counts (myCount int);

  2. manually insert a single record with a value of 0 for column myCount.
    (Never add more records, just use this one for all your counters.)
    ie., INSERT INTO counts (myCount) VALUES (0);

Then, run this code each time you want to increment counter myCount by one:

<?php
  require_once('connect.php');
  $cn = new mysqli($servername, $username, $password, $dbname);
  if(!$cn->connect_error){$cn->query("UPDATE counts SET myCount=myCount+1");}
?>
  • connect.php is a simple connection info file.
  • This code (intentionally) produces no output, even if there's a problem.

Comments

0

you can use the following query to update.

$sql = "update your_table
set col1= col1 + (some number)
where id = (some condition)";

Comments

-1

You can use update query. Example

$update_sql = "update tablename set col1 = col1 + 1 where id = 1";

(ID may be any unique key value of a row in your MySQL table for which the value is to be incremented)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.