我正在使用以下PHP在MySql数据库中为表值添加1,并在每次执行代码时更新数据库。
function create_update() {
$user_id = $_SESSION['user_id'];
$con = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$numberofupdates = number_of_updates(); //'number_of_updates()' gets an INT from the database
settype($numberofupdates, "integer"); //set the number to an INT if it already is not
$spare_update_id = $numberofupdates + 1; //get number and add 1
mysqli_query($con,"UPDATE members SET updates=$spare_update_id WHERE id = $user_id"); //update the value to the database
}
代码工作正常并更新到数据库,但似乎每次都将值更新为1。如果我手动将数据库值设置为4并运行代码,则它应该在5时将值设置回1。
感谢任何帮助!
答案 0 :(得分:0)
如果我理解你的问题,那么你只需要1个mysql查询
function create_update() {
$user_id = $_SESSION['user_id'];
$con = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE members SET updates = (updates + 1) WHERE id = $user_id");
}
答案 1 :(得分:0)
您的代码未运行的原因是因为$numberofupdates
设置为0,所以它总是评估为0 + 1
发生这种情况是因为number_of_updates()
返回零或将其作为整数强制设置为零
而不是所有这些大惊小怪,您可以每次只是运行此查询以增加数量
UPDATE members SET updates = updates + 1 WHERE id = $user_id