MySQL更新不起作用

时间:2012-08-28 20:40:33

标签: php mysql

我想根据用户输入更新我的数据库中的2个字段。我的代码是这样的:

 <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>

然而,虽然我尝试UPDATE时我的数据库连接正常(SELECT显示结果符合预期),但我的数据库中的值保持不变。我检查了$ newpassword和$ newemail的值,它们确实包含了用户每次输入。我在这里缺少什么?

2 个答案:

答案 0 :(得分:4)

您错过了应该围绕密码字段的''(引号)。 改变:

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

为:

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

重要:
尽管它没有相关性,但请不要使用mysql_*函数 - 它已被弃用且易受sql注入攻击。更好地使用PDO或MySQLi。

答案 1 :(得分:2)

这将解决问题,并为sql注入保存(mysql_real_escape_string):

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

但是当然你不应该再使用mysql_*,我只是举例说明你的具体情况。