Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 466
user1710563 Avatar asked Dec 29 '25 22:12

user1710563


1 Answers

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


}

} ?>

like image 55
random_user_name Avatar answered Jan 01 '26 11:01

random_user_name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!