2016-11-15 70 views
0

该任务的想法是允许用户向他们的帐户添加和从他们的帐户中提取“钱”。问题是,我可以加钱,但我不能收回没有得到正确的价值回报

$funds = $_POST['funds']; 
$withdraw_or_add = $_POST['list']; 

if($withdraw_or_add == "add") 
{ 
    $sql = "UPDATE users SET userFunds = '".$funds."' WHERE userId = 1"; 
} 
else 
{ 
    $info = mysql_query("SELECT * FROM users WHERE userId = '1'"); 
    $info = mysql_fetch_assoc($info); 
    $new_fund = $info['userFunds'] - $funds; 
    $sql = "UPDATE users SET userFunds = '".$new_fund."' WHERE userId = 1"; 
} 


mysql_select_db('details_db'); 
$retval = mysql_query($sql, $conn); 

if(! $retval) { 
    die('Could not update data: ' . mysql_error()); 
} 

echo "Updated data successfully\n"; 

mysql_close($conn); 

因此,举例来说,假设$fund = 5$info['userFunds'] = 20那么变量$new_fund应该15。但相反,它等于-5。如果任何人都可以帮助它,将不胜感激。

+6

***请[停止使用'mysql_ *'功能](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。*** [这些扩展名](http://php.net/manual/en/migration70.removed-exts-sapis.php)已在PHP 7中删除。了解[prepared](http://en.wikipedia.org/wiki/Prepared_statement)语句[PDO](http://php.net/manual/en/pdo.prepared-statements.php)和[MySQLi](http://php.net/manual/en/mysqli.quickstart。 prepared-statements.php)并考虑使用PDO,[这真的很简单](http://jayblanchard.net/demystifying_php_pdo.html)。 –

+5

[Little Bobby](http://bobby-tables.com/)说*** [你的脚本存在SQL注入攻击风险。](http://stackoverflow.com/questions/60174/how-can- I-防止-SQL注入式-PHP)***。即使[转义字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)是不安全的! *** SQL注入!*** *这不仅仅是用于早餐!* –

+2

您需要先连接到您的数据库,然后才能查询,以及$ conn'与此窗体一起定义在哪里? –

回答

1

首先顶部的页面你把用过的数据库连接相关的代码:

$conn = mysql_connect('localhost', 'user', 'pass'); 
mysql_select_db('details_db'); 

然后波纹管和后mysql_

$funds = $_POST['funds']; 
$withdraw_or_add = $_POST['list']; 

if($withdraw_or_add == "add") 
{ 
    $sql = "UPDATE users SET userFunds = '".$funds."' WHERE userId = 1"; 
} 
else 
{ 
    $info = mysql_query("SELECT * FROM users WHERE userId = '1'"); 
    $info = mysql_fetch_assoc($info); 
    $new_fund = $info['userFunds'] - $funds; 
    $sql = "UPDATE users SET userFunds = '".$new_fund."' WHERE userId = 1"; 
} 


//mysql_select_db('details_db'); 
$retval = mysql_query($sql, $conn); 

if(! $retval) { 
    die('Could not update data: ' . mysql_error()); 
} 

echo "Updated data successfully\n"; 

mysql_close($conn); 

注意去除mysql_select_db('details_db');线:请停止使用mysql_*功能。 mysql_*extensions已在PHP 7中删除。请使用PDOMySQLi

+0

这有效。非常感谢你! –