user4846835
user4846835

Reputation:

How to increment value in MySQL with PHP mysqli

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.

Upvotes: 1

Views: 5216

Answers (4)

SM Imtiaz Hussain
SM Imtiaz Hussain

Reputation: 447

you can use the following query to update.

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

Upvotes: 0

ashleedawg
ashleedawg

Reputation: 21639

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.

Upvotes: 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)

Upvotes: -1

RiggsFolly
RiggsFolly

Reputation: 94672

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";

Upvotes: 6

Related Questions