问题
I've written the below function to update a value in a MySQLi database table. I'm not receiving any errors, but the value is also not updating. I can't see what's going wrong.
function update_hangman_highscore($user, $user_highscore){
echo 'Update highscore called. High score to update is '.$user_highscore.' for '.$user;
$db = "localhost";
$user = "phpuser";
$pwd = "Ninja1995";
$database = "ninja_comments";
$link = mysqli_connect($db, $user, $pwd)or die(mysqli_connect_error());
mysqli_select_db($link, $database) or die(mysqli_error($link));
$result = mysqli_query($link, "UPDATE users SET hangman_highscore = '$user_highscore' WHERE username = '$user';") or die(mysqli_error());
}
I'm calling the function using:
if($_SESSION['score'] > $_SESSION['user_highscore']){
update_hangman_highscore($_SESSION['user'], $_SESSION['score']);
$_SESSION['message'] = 'Too many wrong guesses. You died, but you also achieved a new personal highscore!';
}
I've used an echo in the function (see first line) to verify that the function is being called. This also tells me that $high_score and $user parameters are being passed properly. I can also replace these variables with actual values, and the function works properly. So at this point, I'm also out of troubleshooting ideas. Any help would be much appreciated.
回答1:
You are using the $user
variable twice, and that's rewriting the value. You should rename it.
Try with
function update_hangman_highscore($user, $user_highscore){
echo 'Update highscore called. High score to update is '.$user_highscore.' for '.$user;
$db = "localhost";
$db_user = "phpuser";
$pwd = "Ninja1995";
$database = "ninja_comments";
$link = mysqli_connect($db, $db_user, $pwd)or die(mysqli_connect_error());
mysqli_select_db($link, $database) or die(mysqli_error($link));
$result = mysqli_query($link, "UPDATE users SET hangman_highscore = '$user_highscore' WHERE username = '$user';") or die(mysqli_error());
}
来源:https://stackoverflow.com/questions/20873432/use-php-to-update-a-value-in-a-mysqli-database-table