Morgan Clarke Morgan Clarke - 22 days ago 9
MySQL Question

SQL update for specific user

I am working on a user account system and I am needing to update records in a SQL database. I have tried looking it up but all the solutions I have found don't seem to work. My table looks something like this

userId userName userCoins
30 Bob 0


And I am wanting to update the userName so it looks like this

userId userName userCoins
30 jim 0


-

<?php
ob_start();
session_start();
include_once 'dbconnect.php';

$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
if ( isset($_POST['btn-signup']) ) {
//This is where I am trying to update

UPDATE users SET userName = 'jim' WHERE userCoins=0;
}
?>
<!DOCTYPE html>
<html>
<?php header("Access-Control-Allow-Origin: http://www.py69.esy.es"); ?>
<head></head>
<body>
<center>
<h3>Welcome, <?php echo $userRow['userName']; ?>. You Currently Have <span id="services"><?php echo $userRow['userCoins']; ?></span> Service Coins</h3>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicons glyphicons-lock"></span></span>
<input type="text" id="emp_id" name="sender" class="form-control" placeholder="Enter Your Wallet Key" value="<?php echo $row['userCoins']; ?>" maxlength="15" />
<span class="text-danger"><?php echo $error; ?></span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-signup">Sign Up</button>
</div>
</center>
</body>
</html>
<?php ob_end_flush(); ?>

Answer

You need to use the function and use quotes around it as you did (similarly) for the SELECT:

if ( isset($_POST['btn-signup']) ) {
        //This is where I am trying to update

       mysql_query("UPDATE users SET userName = 'jim' WHERE userCoins=0");
    }

You're also using an old API and are open to an sql injection.

Use a prepared statement.

References:

and as stated in comments:

Why are you updating based on userCoins = 0? This will update EVERY user's name that has zero (no) coins. Is that really what you want to do? – Charles Bretana

So, you may have to add an additional clause.

You also need to make sure that the $_SESSION['user'] array does indeed contain a value. Otherwise, your query will fail.

Check for errors: