我尝试在调用函数时使用总用户数更新表。我需要做的是抓住以前的使用次数,并添加一个。我对如何解决这个问题有一个很好的总体思路,但我不太清楚如何获得各自用途的唯一ID。这就是我到目前为止......
<?php
$query = $conn->query('select name, uses from users');
$i = 0;
while($r = $query->fetch(PDO::FETCH_OBJ)){
$name[$i] = $r->name;
$uses[$i] = $r->uses;
$i = $i+1;
}
if(isset($_POST['mName']))
{
$mName = urldecode($_POST['mName']);
$mUses = $uses + 1;
"UPDATE users
SET uses=:uses WHERE name=:name";
$stmt = $conn->prepare($sqlUPDATE);
$stmt->bindParam(':uses', $mUses);
$stmt->bindParam(':name', $mName);
$stmt->execute();
?>
我可以看到我的问题是我将使用变量分配给数组,我不知道如何使用特定于用户名。这是一个我丢失的简单SQL查询吗?
答案 0 :(得分:1)
You can store the data in an array called $uses
with the key being the user name and the value being the number of uses. Then if you detect a POST with the mName parameter set, you can reference your $uses
array with that name and get the number of uses, and add 1.
<?php
$query = $conn->query('select name, uses from users');
while($r = $query->fetch(PDO::FETCH_OBJ)){
$uses[$r->name] = $r->uses;
}
if(isset($_POST['mName'])) {
$mName = urldecode($_POST['mName']);
$mUses = $uses[$mName] + 1;
$sqlUPDATE = "UPDATE users SET uses=:uses WHERE name=:name";
$stmt = $conn->prepare($sqlUPDATE);
$stmt->bindParam(':uses', $mUses);
$stmt->bindParam(':name', $mName);
$stmt->execute();
}
?>
Though there is no error checking and handling in here. If there happens to be a POST with mName and that name doesn't exist, nothing will update, but nothing will insert for new users. Also, instead of using a name, it would be better to use an id for the user if possible.