yiannis
yiannis

Reputation: 430

MySQL update doesn't work

I want to update 2 of my database's fields according to user input.My code is something like this:

 <body>
<?php
 $db_server["host"] = "localhost"; //database server
$db_server["username"] = "root"; // DB username
$db_server["password"] = "mypass"; // DB password
$db_server["database"] = "mudb";// database name

$dbc = mysql_connect($db_server["host"], $db_server["username"], $db_server["password"]);
mysql_select_db($db_server["database"], $dbc);
$user =  $_COOKIE['mycookie'];

    $q = "SELECT * FROM members WHERE username='$user'"; 
    $r = mysql_query( $q,$dbc);
    while ($row = mysql_fetch_array($r, MYSQLI_ASSOC)) { 
    echo 'username: '.$row['username'], '<br/>';

    $password=$row['password'];
?>

<form method="post" id="changepasswordform" > 
<input type="password" id="newpassword" name="newpassword"/>
<input type="submit"  name="changepasswordbutton"  >  
       </form>

<?php

        echo 'email:        '.$row['email'], '<br/>'; 
        }
?>

<form method="post" id="changeemailform" >  

        <input type="text" id="newemail" name="newemail"/>

       <input type="submit" value="αλλαγή"  name="changeemailbutton"  >
       </form>

<?php
}


    if (isset($_POST['changepasswordbutton'])){

                       $newpassword=$_POST['newpassword'];
                $q2 = "UPDATE members SET password=$newpassword WHERE username='$user'"; 

                $r2 = mysql_query($q2,$dbc);

}   

if (isset($_POST['changeemailbutton'])){
                    $newemail=$_POST['newemail'];
                    $q3 = "UPDATE members SET email=$newemail WHERE username='$user'"; 
                $r3 = @mysql_query( $q3,$dbc);  
}
?>
</body>

However although my connection to my db is ok(SELECT displays results as expected) when i try to UPDATE , the values inside my db remain the same.I checked the values of $newpassword and $newemail and they do contain the user inputs each time.What am i missing here?

Upvotes: 1

Views: 2387

Answers (2)

Nir Alfasi
Nir Alfasi

Reputation: 53545

You're missing the '' (quotes) that supposed to surround the password field. change:

UPDATE members SET password=$newpassword WHERE username='$user'

to:

UPDATE members SET password='{mysql_real_escape_string($password)}' 
WHERE username='{mysql_real_escape_string($user)}'

IMPORTANT:
And even though it's not related, please don't use mysql_* functions - it's deprecated and vulnerable to sql-injection. Better use PDO or MySQLi.

Upvotes: 4

arnoudhgz
arnoudhgz

Reputation: 1284

This will do the trick and is save for sql injection (mysql_real_escape_string):

 $q2 = "UPDATE members SET 
   password='". mysql_real_escape_string($password) ."' 
   WHERE username='". mysql_real_escape_string($user) ."';

But off course you shouldn't use mysql_* anymore, I'm just giving an example for your specific case.

Upvotes: 2

Related Questions