简体   繁体   中英

Adding integers from a variable to mysql column

i'm wondering how can i add an integer which i have assigned in a variable to a mysql table's column using INSERT.

this is my code:

//Connect to database
include ("connnect.php");

$countv = "10"
$insert  = ("INSERT INTO table1 (id,count) VALUES ('$id',+$countv)";
mysql_query($insert) or die(mysql_error());

the count column is set to int and the default value is '0' Normally i add 10 using +10 , but now i want to try adding it via a variable. so i set "count" column to add $countv's value interger.

this script can add 10 to the column count, but when i try it the second time( which is using UPDATE table1 SET count = +$countv WHERE id='123' ) , it still remains as 10. is there any mistakes i'm making or is there a better way to do this?

Update script

  mysql_query("UPDATE table1 SET count = + $countv WHERE id='123'")
            or die(mysql_error()); 

Thanks and have a nice day.

(SOLVED : i forgotten to add count infront of + $countv in the update script. thanks for those who help)

试试这个语法

update table1 set count = count + $countv where id = '123'

Your update query should be:

$query ="UPDATE table1 `count` = `count` + $countv WHERE id=123";

Mind you, count is a reserved word in MySQL so it should be in backticks

you can do this in two ways: - first retrieve the value, update it with php and write it back to the mysql table - or a simple sql query: UPDATE leaderb SET count = count + 10 WHERE ....

since you are inserting in mysql you don't have an initial value there. so you should use update to change an existing row/record.

试试这个:

UPDATE table1 SET count = count+$countv WHERE id = '123'

i have no idea how it worked for you since u add the names '$id' and '$countv' instead of thier values.

i think you should swap that:

$insert  = "INSERT INTO table1 (id,count) VALUES ('$id',+$countv)";

with:

$insert  = "INSERT INTO table1 (id,count) VALUES ('$id', +" . $countv . ")";

if id is also a php int (i assume so) u need:

$insert  = "INSERT INTO table1 (id,count) VALUES ('" . $id . "', +" . $countv . ")";

tell me how it went :)

Its because you are replacing the value each time with 10. The program does not know the number that is in the database.

You need to retrieve the data first, update the value and then place it back in the database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM