Zardiw
Zardiw

Reputation: 93

MySql Fetch Array manipulation

Ok..I know how to get a data record from a MySql table...and I want to change data in that record and update the table.

My question is...can you actually manipulate that data from the result row, and subsequently use those in the update statement?

For example.

Let's say the table rows have 2 fields: Name, YearlyEarn.

And once a month I want to add that month's income to the YearlyEarn field for each person.

Assume we already did the Select statement for someone who's name is in $CurrentName. And we then get their record.

$DataRow = mysql_fetch_array($result):

Can you do this:

$DataRow["YearlyEarn"] = $DataRow["YearlyEarn"] + $MonthEarn;

$query = "UPDATE EarnTable SET YearlyEarn = '$DataRow["YearlyEarn"]'    
`WHERE Name = '$CurrentName'" ;

$UpdResult = mysql_query($query) or die(mysql_error());

OR.....should I put the data into intermediate fields, manipulate it..and then use those fields in the update statement?

Upvotes: 1

Views: 485

Answers (3)

Barmar
Barmar

Reputation: 781716

You can use:

$query = "UPDATE EarnTable SET YearlyEarn = '$DataRow[YearlyEarn]' WHERE Name = '$CurrentName'" ;

When you're interpolating an array reference, the key is automatically quoted.

or:

$query = "UPDATE EarnTable SET YearlyEarn = '{$DataRow["YearlyEarn"]}' WHERE Name = '$CurrentName'" ;

Inside {...}, you can put any variable expression and it will be evaluated and interpolated.

Upvotes: 0

eggyal
eggyal

Reputation: 125925

Yes, you can:

UPDATE EarnTable
SET    YearlyEarn = YearlyEarn + 123
WHERE  Name = 'abc'

Upvotes: 1

You should use prepared statements, like PDO. The mysql_* is outdated. But if not doing so, you should consider changing your query from:

$query = "UPDATE EarnTable SET YearlyEarn = '$DataRow["YearlyEarn"]'`WHERE Name = '$CurrentName'" ;

to:

$query = "UPDATE EarnTable SET YearlyEarn = `" . $DataRow['YearlyEarn'] . "` WHERE Name = `$CurrentName`" ;

Upvotes: 1

Related Questions