PHP mySQL Update Query

Discussion in 'PHP' started by Waizujin, Jun 10, 2008.

  1. #1
    I have this code:
    
    			$Spy = mysql_real_escape_string($_POST['Spy']);
    			$Guard = mysql_real_escape_string($_POST['Guards']);
    			$Swordsmen = mysql_real_escape_string($_POST['Swordsmen']);
    			$Spearmen = mysql_real_escape_string($_POST['Spearmen']);
    			$Archer = mysql_real_escape_string($_POST['Archer']);
    			$Macemen = mysql_real_escape_string($_POST['Macemen']);
    			$grab_unit_cost = mysql_query("SELECT Unit_Cost FROM " .$_SESSION['Server']. "_Units") or die(mysql_error());
    			while($row = mysql_fetch_array($grab_unit_cost))
    			{
    				$Unit_Cost += $row['Unit_Cost'];
    			}
    			$Buy_Units = "UPDATE " .$_SESSION['Server']. "_kingdoms SET Spy = Spy + $Spy, Guard = Guard + $Guard, Swordsmen = Swordsmen + $Swordsmen, Spearmen = Spearmen + $Spearmen, Archer = Archer + $Archer, Macemen = Macemen + $Macemen, Kingdom_Gold = Kingdom_Gold - $Unit_Cost";
    			mysql_query($Buy_Units) or die(mysql_error());
    			echo 'Units successfully bought, <a href="game.php?act=Training">continue training</a>.';
    
    Code (markup):
    It gives me this error:
    Any idea what I am doing wrong? Well, I know what I am doing wrong but not sure how to do it right.

    Thanks,
    -Ryu
     
    Waizujin, Jun 10, 2008 IP
  2. mehmetm

    mehmetm Well-Known Member

    Messages:
    134
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    110
    #2
    try this query

    $Buy_Units = "UPDATE " .$_SESSION['Server']. "_kingdoms SET Spy = Spy + '" .$Spy. "', Guard = Guard + '" .$Guard. "', Swordsmen = Swordsmen + '" .$Swordsmen. "', Spearmen = Spearmen + '" .$Spearmen. "', Archer = Archer + '" .$Archer. "', Macemen = Macemen + '" .$Macemen. "', Kingdom_Gold = Kingdom_Gold - '" .$Unit_Cost. "'";
    Code (markup):
     
    mehmetm, Jun 11, 2008 IP
  3. Lordo

    Lordo Well-Known Member

    Messages:
    2,082
    Likes Received:
    58
    Best Answers:
    0
    Trophy Points:
    190
    #3
    You can simply add intval in each mysql_real_escape_string line. Example:

    $Spy = intval(mysql_real_escape_string($_POST['Spy']));

    The issue is that the script handles the variables you want to add to the database as text not integer. So, when they are empty, their value is "" instead of 0. By adding intval, you force it to make them 0 if they are empty.
     
    Lordo, Jun 11, 2008 IP