更改用户名表单无效

时间:2014-09-20 15:45:10

标签: php html mysql sql pdo

我是PHP新手但是当我尝试创建更改用户名表单时,我只是收到错误。 “无法运行查询:SQLSTATE [HY093]:参数号无效:参数未定义”

我不确定导致此错误的原因,但我只是在添加用户名输入表单时才会收到错误。

我已将edit_account和配置文件上传到pastebin,供大家查看。

先谢谢

唯一

--------链接--------

Common.php - > http://pastebin.com/zTHmef5V

edit_account.php - > http://pastebin.com/t8faiSyv

--------代码--------

的common.php:

<?php 

// These variables define the connection information for your MySQL database 
$username = "root"; 
$password = ""; 
$host = "localhost"; 
$dbname = "website"; 

// UTF-8 is a character encoding scheme that allows you to conveniently store 
// a wide varienty of special characters, like ¢ or €, in your database. 
// By passing the following $options array to the database connection code we 
// are telling the MySQL server that we want to communicate with it using UTF-8 
// See Wikipedia for more information on UTF-8: 
// http://en.wikipedia.org/wiki/UTF-8 
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 

// A try/catch statement is a common method of error handling in object oriented code. 
// First, PHP executes the code within the try block.  If at any time it encounters an 
// error while executing that code, it stops immediately and jumps down to the 
// catch block.  For more detailed information on exceptions and try/catch blocks: 
// http://us2.php.net/manual/en/language.exceptions.php 
try 
{ 
    // This statement opens a connection to your database using the PDO library 
    // PDO is designed to provide a flexible interface between PHP and many 
    // different types of database servers.  For more information on PDO: 
    // http://us2.php.net/manual/en/class.pdo.php 
    $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
} 
catch(PDOException $ex) 
{ 
    // If an error occurs while opening a connection to your database, it will 
    // be trapped here.  The script will output an error and stop executing. 
    // Note: On a production website, you should not output $ex->getMessage(). 
    // It may provide an attacker with helpful information about your code 
    // (like your database username and password). 
    die("Failed to connect to the database: " . $ex->getMessage()); 
} 

// This statement configures PDO to throw an exception when it encounters 
// an error.  This allows us to use try/catch blocks to trap database errors. 
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

// This statement configures PDO to return database rows from your database using an associative 
// array.  This means the array will have string indexes, where the string value 
// represents the name of the column in your database. 
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 

// This block of code is used to undo magic quotes.  Magic quotes are a terrible 
// feature that was removed from PHP as of PHP 5.4.  However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to 
// prevent them from causing problems.  For more information on magic quotes: 
// http://php.net/manual/en/security.magicquotes.php 
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) 
{ 
    function undo_magic_quotes_gpc(&$array) 
    { 
        foreach($array as &$value) 
        { 
            if(is_array($value)) 
            { 
                undo_magic_quotes_gpc($value); 
            } 
            else 
            { 
                $value = stripslashes($value); 
            } 
        } 
    } 

    undo_magic_quotes_gpc($_POST); 
    undo_magic_quotes_gpc($_GET); 
    undo_magic_quotes_gpc($_COOKIE); 
} 

// This tells the web browser that your content is encoded using UTF-8 
// and that it should submit content back to you using UTF-8 
header('Content-Type: text/html; charset=utf-8'); 

// This initializes a session.  Sessions are used to store information about 
// a visitor from one web page visit to the next.  Unlike a cookie, the information is 
// stored on the server-side and cannot be modified by the visitor.  However, 
// note that in most cases sessions do still use cookies and require the visitor 
// to have cookies enabled.  For more information about sessions: 
// http://us.php.net/manual/en/book.session.php 
session_start(); 

edit_account.php:

<?php 

// First we execute our common code to connection to the database and start the session 
$commonPath = $_SERVER['DOCUMENT_ROOT'];
$commonPath .= "/include/common.php";
require($commonPath); 

// At the top of the page we check to see whether the user is logged in or not 
if(empty($_SESSION['user'])) 
{ 
    // If they are not, we redirect them to the login page. 
    header("Location: include/login.php"); 

    // Remember that this die statement is absolutely critical.  Without it, 
    // people can view your members-only content without logging in. 
    die("Redirecting to login.php"); 
} 

// This if statement checks to determine whether the edit form has been submitted
// If it has, then the account updating code is run, otherwise the form is displayed 
if(!empty($_POST)) 
{ 
    // Make sure the user entered a valid E-Mail address 
    if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) 
    { 
        die("Invalid E-Mail Address"); 
    } 

    // If the user is changing their E-Mail address, we need to make sure that 
    // the new value does not conflict with a value that is already in the system. 
    // If the user is not changing their E-Mail address this check is not needed.
    if($_POST['email'] != $_SESSION['user']['email']) 
    { 
        // Define our SQL query 
        $query = " 
            SELECT 
                1 
            FROM users 
            WHERE 
                email = :email 
        "; 

        // Define our query parameter values 
        $query_params = array( 
            ':email' => $_POST['email'] 
        ); 

        try 
        { 
            // Execute the query 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex) 
        { 
            // Note: On a production website, you should not output $ex->getMessage(). 
            // It may provide an attacker with helpful information about your code.  
            die("Failed to run query: " . $ex->getMessage()); 
        } 

        // Retrieve results (if any) 
        $row = $stmt->fetch(); 
        if($row) 
        { 
            die("This E-Mail address is already in use"); 
        } 
    } 

    if($_POST['username'] != $_SESSION['user']['username']) 
    { 
        // Define our SQL query 
        $query = " 
            SELECT 
                1 
            FROM users 
            WHERE 
                username = :username 
        "; 

        // Define our query parameter values 
        $query_params = array( 
            ':username' => $_POST['username'] 
        ); 

        try 
        { 
            // Execute the query 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex) 
        { 
            // Note: On a production website, you should not output $ex->getMessage(). 
            // It may provide an attacker with helpful information about your code.  
            die("Failed to run query: " . $ex->getMessage()); 
        } 

        // Retrieve results (if any) 
        $row = $stmt->fetch(); 
        if($row) 
        { 
            die("This username is already in use"); 
        } 
    } 

    // If the user entered a new password, we need to hash it and generate a fresh salt 
    // for good measure. 
    if(!empty($_POST['password'])) 
    { 
        $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647)); 
        $password = hash('sha256', $_POST['password'] . $salt); 
        for($round = 0; $round < 65536; $round++) 
        { 
            $password = hash('sha256', $password . $salt); 
        } 
    } 
    else 
    { 
        // If the user did not enter a new password we will not update their old one. 
        $password = null; 
        $salt = null; 
    } 

    // Initial query parameter values 
    $query_params = array( 
        ':email' => $_POST['email'], 
        ':user_id' => $_SESSION['user']['id'], 
    ); 

    // If the user is changing their password, then we need parameter values 
    // for the new password hash and salt too. 
    if($password !== null) 
    { 
        $query_params[':password'] = $password; 
        $query_params[':salt'] = $salt; 
    } 

    // Note how this is only first half of the necessary update query.  We will dynamically 
    // construct the rest of it depending on whether or not the user is changing 
    // their password. 
    $query = " 
        UPDATE users 
        SET 
            email = :email 
    "; 

    $query = " 
        UPDATE users 
        SET 
            username = :username 
    "; 

    // If the user is changing their password, then we extend the SQL query 
    // to include the password and salt columns and parameter tokens too. 
    if($password !== null) 
    { 
        $query .= " 
            , password = :password 
            , salt = :salt 
        "; 
    } 

    // Finally we finish the update query by specifying that we only wish 
    // to update the one record with for the current user. 
    $query .= " 
        WHERE 
            id = :user_id 
    "; 

    try 
    { 
        // Execute the query 
        $stmt = $db->prepare($query); 
        $result = $stmt->execute($query_params); 
    } 
    catch(PDOException $ex) 
    { 
        // Note: On a production website, you should not output $ex->getMessage(). 
        // It may provide an attacker with helpful information about your code.  
        die("Failed to run query: " . $ex->getMessage()); 
    } 

    // Now that the user's E-Mail address has changed, the data stored in the $_SESSION 
    // array is stale; we need to update it so that it is accurate. 
    $_SESSION['user']['email'] = $_POST['email']; 
    $_SESSION['user']['username'] = $_POST['username']; 

    // This redirects the user back to the members-only page after they register 
    header("Location: include/private.php"); 

    // Calling die or exit after performing a redirect using the header function 
    // is critical.  The rest of your PHP script will continue to execute and 
    // will be sent to the user if you do not die or exit. 
    die("Redirecting to private.php"); 
}  

edit_account.php表单:

    <?php
    include ('include/header.php');
    include ('include/slider.php'); ?>
    <div id="edit-account">
    <h1>Edit Account</h1> 
    <center>
    <form action="edit_account.php" method="post"> 
    Username:<br /> 
    <b><?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?></b> 
    <br /><br /> 
    Change Username:<br /> 
    <input type="text" name="username" value="<?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?>" /><br /> 
    E-Mail Address:<br /> 
    <input type="text" name="email" value="<?php echo htmlentities($_SESSION['user']['email'], ENT_QUOTES, 'UTF-8'); ?>" /> 
    <br /><br /> 
    Password:<br /> 
    <input type="password" name="password" value="" /><br /> 
    <i>(leave blank if you do not want to change your password)</i> 
    <br /><br /> 
    <input type="submit" value="Submit Changes" /> 
    </form>
    </center>
    </div>
    <?php
    include ('include/footer.php');
?>

1 个答案:

答案 0 :(得分:1)

在第二个代码段的最后部分进行标记更改:

  • 设置参数:username的值,而不是:email
  • 删除UPDATE语句的多余第一个开头。

所以这应该是:

 // Initial query parameter values 
$query_params = array( 
    ':username' => $_POST['username']      // set the value for the parameter :username
    // ':email' => $_POST['email'],        // that's not needed here
    ':user_id' => $_SESSION['user']['id'], 
); 

// If the user is changing their password, then we need parameter values 
// for the new password hash and salt too. 
if($password !== null) 
{ 
    $query_params[':password'] = $password; 
    $query_params[':salt'] = $salt; 
} 

/* remove this section
// Note how this is only first half of the necessary update query.  We will dynamically 
// construct the rest of it depending on whether or not the user is changing 
// their password. 
$query = " 
    UPDATE users 
    SET 
        email = :email 
"; 
       // because you overwrite this in the next statement:
*/

$query = " 
    UPDATE users 
    SET 
        username = :username 
";