user1710563
user1710563

Reputation: 387

How do I save text from a textarea into a MySQL database with PHP when a Save button is clicked?

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>

Upvotes: 3

Views: 3570

Answers (1)

random_user_name
random_user_name

Reputation: 26160

First: You should use PDO to connect to your database, not mysql. Mysql is being deprecated, and is prone to SQL Injection attacks and therefore NOT safe to use in web applications.

With that caveat, I will reply using mysql since that is what you are using.

It's not too difficult. Of course without the table structure, or the code from your form, the below has to use example field names, and assumes you store the user id in a $_SESSION variable:

<?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);


}

} ?>

Upvotes: 2

Related Questions