Morgan Clarke Morgan Clarke - 2 months ago 13
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


include_once 'dbconnect.php';

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

UPDATE users SET userName = 'jim' WHERE userCoins=0;
<!DOCTYPE html>
<?php header("Access-Control-Allow-Origin:"); ?>
<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 class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-signup">Sign Up</button>
<?php ob_end_flush(); ?>


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.


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: