Jump to content

[SOLVED] Checking If a Value Above a Certain Number Exists in a DB and Subtracting/Adding


Akenatehm

Recommended Posts

Hey Guys,

 

I have ripped my hair out trying to figure out why this does not work:

 

$checkgold = mysql_query("SELECT gold FROM characters WHERE name = '$charactername'");
if (!$checkdb)
{
die('Could Not Find Gold Amount:' . mysql_error());
}
if ('gold' < 10)
{
echo "Not Enough Gold";
}

 

I am trying to get it to check if the user has more than 10 gold.

 

Also I have no idea how I would go about adding/subtracting an amount from a field in the DB. Say the user has 100 gold. Then they teleport themselves somewhere costing 10 gold and it subtracts 10 from the 100 gold in the field in their DB.

 

Help would be appreciated!

Cody

Comparing 'gold' to 10 doesn't make sense.  gold is a literal string, so why compare it numerically to an integer?

 

 

mysql_query returns a resource (or false on error), and you must extract the results from the resource.

 

 

You would want to use either mysql_result or mysql_fetch_*.

 

For example:

 

$gold = mysql_result($checkgold, 0);

Really there is no need to SELECT, just try to UPDATE and that will do what you want...

 


<?php

$amount = 10;

$charactername = 'doppy';

mysql_connect ( 'localhost', 'seven', 'dwarfs' );

mysql_select_db ( 'snow_white' );

$query = "UPDATE characters SET gold = gold - " . $amount . " WHERE name = '" . $charactername . "' AND gold >= '" . $amount . "';";

mysql_query ( $query );

if ( mysql_affected_rows () == 1 )
{
// Wow, doppy can teleport
}
else
{
// Awe, doppy don't have enough gold to teleport
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.