2012-10-30 37 views
2

我在HTML中有一个textarea,登录用户可以输入和保存注释。我使用下面的脚本从数据库单击保存按钮时,如何使用PHP将textarea中的文本保存到MySQL数据库中?

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

这工作都好得很,但检索保存的笔记现在 - 我怎么保存用户的笔记(文本域)单击保存按钮时所做的更改?

编辑:

这里是形式本身:

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

这非常广泛。开始阅读[关于'UPDATE'语句](http://dev.mysql.com/doc/refman/5.0/en/update.html),然后是[PHP中的$ _POST超全局](http:// php.net/manual/en/reserved.variables.post.php)我们没有足够的信息来给出任何特定的答案 - 你的表单发布到PHP,你逃避输入,并执行一个'UPDATE'语句(或'INSERT'用于新行。 –

+0

textarea上没有'name ='属性,这意味着当提交表单时无法从'$ _POST'变量中获取它。跟踪用户ID? –

回答

2

首先:你应该使用PDO连接到您的数据库,而不是MySQL的。 Mysql is being deprecated,并且倾向于SQL Injection attacks,因此在Web应用程序中不安全。

有了这样的警告,我会回复使用MySQL,因为这是你使用的。

这并不难。当然不表结构,或从表单中的代码,下面有应用实例字段名,并假定你存储在$_SESSION变量的用户ID:

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


} 

} >

+0

我编辑了原始问题 - 这确实有帮助 – user1710563

相关问题