【问题标题】:How do I save text from a textarea into a MySQL database with PHP when a Save button is clicked?单击“保存”按钮时,如何使用 PHP 将文本从 textarea 保存到 MySQL 数据库中?
【发布时间】:2012-10-30 00:09:03
【问题描述】:

我有一个 HTML 文本区域,登录用户可以在其中输入和保存注释。我使用以下脚本从数据库中检索保存的笔记

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

这一切都很好,但现在 - 当点击“保存”按钮时,如何保存用户对注释 (textarea) 所做的更改?

编辑:

这是表单本身:

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

【问题讨论】:

  • 这个范围很广。开始阅读about UPDATE statements,然后是$_POST superglobal in PHP 我们没有足够的信息来给出任何具体的答案——您的表单发布到 PHP,您转义输入,然后执行 UPDATE 语句(或 @ 987654328@ 用于新行。
  • 您在 textarea 上没有 name= 属性,这意味着在提交表单时无法从 $_POST 变量中获取它。另外,您如何/在哪里跟踪用户 ID?

标签: php mysql insert save


【解决方案1】:

首先:您应该使用PDO 连接到您的数据库,而不是mysql。 Mysql is being deprecated,并且容易出现 SQL Injection attacks,因此在 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);


}

} ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 2014-12-18
    • 1970-01-01
    • 2013-12-15
    • 2021-08-25
    • 2013-12-24
    • 2021-10-31
    相关资源
    最近更新 更多