William Willi William Willi - 10 days ago 5
PHP Question

Adding constant to values in Mysql and updating the values to the result

I have got MySQL table with three columns 'primary Key','debit_cash','user_id' So now i want to update the debit_cash values to the corresponding user_id by adding "15" to the value already present. The debit_cash is in VARCHAR so i tried converting to int and sum it , but still the values in MySQL is not changing .

Here is my code:

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$user_id = $_POST['user_id'];


//importing database connection script
require_once('dbConnect.php');

//Creating sql query
$sql = "SELECT cos_details.debit_cash AS debitCash,
(convert(int, debit_cash)+15) AS updatedDebitCash
FROM cos_details
UPDATE cos_details SET debit_cash = '$updatedDebitCash'
WHERE user_id = $user_id";

//Updating database table
if(mysqli_query($con,$sql)){
echo 'Updated Successfully';
}else{
echo 'Could Not Update Try Again';
}

//closing connection
mysqli_close($con);
}


Any one please help me.

Answer

Seems that you don't need the select but the update only

  UPDATE cos_details SET debit_cash = cast( (convert(int, debit_cash)+15) as VARCHAR(20))
  WHERE user_id = $user_id

could be that your user_id is a string too so you should surround the value with quote

  UPDATE cos_details SET debit_cash = cast( (convert(int, debit_cash)+15) as VARCHAR(20))
  WHERE user_id = '$user_id'
Comments