Mysql更改用户名查询

时间:2015-02-10 21:27:27

标签: php mysql

我遇到这个问题,我需要更改用户名,因为 它对我网站上的管理员来说是一种特权,但是当它进入mysql端时,我根本不知道,这是它的工作原理: 管理员填写表单(用户名和新用户名) 我需要它来查找用户名id,然后在输入的表单中使用所选的新用户名更改用户名 如果这有助于我的代码到目前为止

<?php
include 'core/init.php';
protect_page();
admin_protect();
include 'includes/overall/header.php';

if (empty($_POST) === false) {
    $required_fields = array('username', 'add');
    foreach($_POST as $key=>$value) {
        if (empty($value) && in_array($key, $required_fields) === true) {
            $errors[] = 'Fields marked with an asterisk are required';
            break 1;
        }
    }
}

    if (empty($errors) === false) {
        if (user_exists($_POST['cusername']) === true) {
            $errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' is taken!';
        }
    }
?>

<?php
if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
    echo 'The username has been succesfully changed!';
} else {
    if (empty($_POST) === false && empty($errors) === true) {
        $cusername = array(
            'username'      => $_POST['username'],
            'cusername'         => $_POST['cusername']
        );

function cusername($cusername) {
    mysql_query("UPDATE users WHERE username = '".$_POST['username']."' SET          username = ".$_POST['cusername']."");
}  
        cusername($cusername);
        header('Location: changeusername.php?success');
        exit();

    } else if (empty($errors) === false) {
        echo output_errors($errors);
    }
?>

<h1>Admin Access Only</h1>
<p>Change a username</p>
        <form action="" method="post">
        <ul>
                <li>
                    Username*:<br>
                    <input type="text" name="username">
                </li>
                <li>
                    New Username*:<br>
                    <input type="text" name="cusername">
                </li>
                <li>
                    <input type="submit" value="Update">
                </li>
        </ul>
        </form>
<?php
}
include 'includes/overall/footer.php';
?>

1 个答案:

答案 0 :(得分:0)

在UPDATE语句中,首先需要SET,然后是WHERE。但正如Marc B指出的那样,你总是需要小心消毒并逃避用户输入的数据。不要相信用户给你的任何东西!在这种情况下,您可以使用mysql_real_escape_string尽管该函数现已弃用,您应该考虑将数据库处理代码更改为MySQLi或PDO_MySQL。

mysql_query("UPDATE users SET username = '".mysql_real_escape_string($_POST['cusername'])."' WHERE username = '".mysql_real_escape_string($_POST['username'])."'");