phpmysqlmysqli

Best way to increment a single column in MySQL table?


I'm fairly new to coding, and have just started on a project for fun. I'm trying to build an RPG game, and I have got to the point where players can fight and take damage. So I want to add a passive health regeneration.

So I was thinking that I would use a cronjob to request a PHP file every 10min and update all players HP with +10.

What I have got with my very poor MySQL knowledge is:

<?php
/* 
 * hp_reg.php, auto updater +10hp to players.
 */
 
    //DATABAS CONNECTION
    $dbserver="my";
    $dbusername ="db";
    $dbpassword ="conection";
    $db ="information";

    //CREATE CONNECTION
    $conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
    $query = "SELECT health FROM users";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_assoc($query);

    $newhp = $result + 10;
    $sql = "INSERT INTO users(health) VALUES ($newhp)";

Which clearly will not work at all! Any tips on what to change in order to get it to work? All pointers are much appreciated.


Solution

  • $sql = "UPDATE users SET health = health + 10";
    

    Updated Code

     <?php
    /* 
    * hp_reg.php, auto updater +10hp to players.
    */
    
    //DATABAS CONNECTION
    $dbserver="my";
    $dbusername ="db";
    $dbpassword ="conection";
    $db ="information";
    
    //CREATE CONNECTION
    $conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
    
    $sql = "UPDATE users SET health = health + 10";
    
    $result = mysqli_query($conn, $sql);