我需要通过添加或减去数值来更新当前的DB字段值。我已经审核了#34;建议的答案"并没有找到解决我的问题的方法。我的数据库中的字段是标题"信用"它的默认值为" 0。"指定的数据库引擎是InnoDB。我使用程序化PHP编码,以下是我目前的代码:
定义变量
$id=$_SESSION['user_id']; //id number for user
$amount=$_POST['Amount']; //value of charges 12 character string
$amount=ltrim($amount, '0'); //eliminates leading 0's
$credit=$amount/1000; //converts value to credits
$credit=number_format($credit, 2); //formats credits with two decimal points
然后我建立数据库连接并执行以下查询
$q="select credits from registration WHERE user_id=$id";
$r=mysqli_query ($dbc, $q);
$update="UPDATE registration SET credits = credits + $credit WHERE user_id=$id";
如果我"回声"变量我看到所有的值,但"更新"失败。使用程序性的PHP编码,需要修改什么来逐步更新"信用"场?
答案 0 :(得分:0)
//**i hope this helps**
<?php
$id=$_SESSION['user_id']; //id number for user
$amount=$_POST['Amount']; //value of charges 12 character string
$amount=ltrim($amount, '0'); //eliminates leading 0's
$credit=$amount/1000; //converts value to credits
$credit=number_format($credit, 2); //formats credits with two decimal points
$credits; // the credits from query select will be stored here
/* edit with your database parameters */
$mysqli = new mysqli($host, $user, $password, $db);
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
mysqli_set_charset($mysqli,"utf8");
if($stmt = $mysqli -> prepare("select credits from registration WHERE user_id=?"))
{
$stmt -> bind_param("i", $id); //'i' means that ? is an integer value, and $id is the parameter for this value
$stmt -> execute();
$stmt -> bind_result($credits);
$stmt -> fetch();
$stmt -> close();
$total=$credits+$credit;
if($stmt = $mysqli->prepare("UPDATE registration SET credits = ? WHERE user_id=?"))
{
$stmt->bind_param("di",$total,$id);
$stmt->execute();
echo 'oki doki';
$stmt->close();
}
}
?>
答案 1 :(得分:0)
关闭,我想提供解决我的问题的编码,它可以帮助任何人查看此帖子。我相信Dante的解决方案使用&#34;准备好的陈述&#34;是最好的,但这是我如何解决我的问题。
代码行添加:
$update="UPDATE registration SET credits=$ttl WHERE user_id=$id";
$r = mysqli_query ($dbc, $update) or trigger_error("Query: $update\n<br />MySQL Error: " . mysqli_error($dbc));
将更新查询修改为:
{{1}}
这很好用,我需要向用户发送消息中的$ ttl和$ credit变量。我希望这会有所帮助。