2

I have a textarea in HTML where a logged in user can enter and save notes. I use the following script to retrieve the saved notes from the database

<?php
function notes() {
    $password = "fake_password";
    $connect = mysql_connect("localhost", "user", $password) or die("Couldn't connect to the database!");
    mysql_select_db("db_name") or die("Couldn't find the database!");

    $query = mysql_query("SELECT * FROM users WHERE notes!=''");
    $numrows = mysql_num_rows($query);

    if ($numrows != 0) {
        while ($row = mysql_fetch_assoc($query)){
            $notes = $row['notes'];
        }

        echo $notes;
    }
}
?>

That works all fine and dandy but now - how do I save the changes the user made to the notes (textarea) when a Save button is clicked?

EDIT:

Here is the form itself:

<div class="row-fluid">
    <div class="span12">
        <br />
        <center><textarea class="input-xxlarge" rows="15"><?php include('includes/func.php'); notes(); ?></textarea>
        <br />
        <button class="btn btn-primary">Save Changes</button>
        </center>
    </div>
</div>
4

1 回答 1

2

首先:您应该使用PDO连接到您的数据库,而不是 mysql。 Mysql 已被弃用,并且容易受到SQL 注入攻击,因此在 Web 应用程序中使用并不安全。

有了这个警告,我将使用 mysql 回复,因为这就是你正在使用的。

这不是太难。当然,如果没有表结构或表单中的代码,下面必须使用示例字段名称,并假设您将用户 ID 存储在$_SESSION变量中:

<?php
    function savenotes() {
        // The database connection code should be moved to a central function/location rather than called in every function
        $password = "fake_password";
        $connect = mysql_connect("localhost", "user", $password) or die("Couldn't connect to the database!");
        mysql_select_db("db_name") or die("Couldn't find the database!");

        // Retreive notes from form
        $notes = $_POST['notes']; // Assumes field is called notes, and you used method=POST
        // Assuming a user can only update their own notes, and that you are storing the user id somewhere
        $userid = $_SESSION['userid']; 
        $query = mysql_query("UPDATE users SET notes ='" . mysql_real_escape_string($notes) . "' WHERE userid = " . (int)$userid);


}

} ?>

于 2012-10-30T00:20:37.790 回答