2012-10-30 72 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

相關問題