I'm trying to update my tables with a total number of uses when a function is called. What I need to do is grab the former number of uses, and add one. I have a pretty good general idea how to go about this, but I don't quite know how to get unique ID's with their respective uses. This is what I have so far...
<?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();
?>
I can see my issue is that I'm assigning the uses variable to an array, I don't know how to get it specific to the username. Is this a simple SQL query I'm missing?
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.