单击保存按钮时,如何使用PHP将文本区域中的文本保存到MySQL数据库中?
我有一个HTML文本区,登录用户可以在其中输入和保存注释。我使用以下脚本从数据库中检索保存的注释单击保存按钮时,如何使用PHP将文本区域中的文本保存到MySQL数据库中?,php,mysql,insert,save,Php,Mysql,Insert,Save,我有一个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
<?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;
}
}
?>
首先:应该使用连接数据库,而不是mysql,并且易于在web应用程序中使用,因此不安全
有了这个警告,我将使用mysql进行回复,因为您正在使用mysql
这不太难。当然,如果没有表结构或表单中的代码,下面必须使用示例字段名,并假设您将用户id存储在$\u会话
变量中:
<?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);
}
这是非常广泛的。开始阅读,然后是“我们几乎没有足够的信息来给出任何具体的答案”——您的表单发布到PHP,退出输入,然后执行UPDATE
语句(或INSERT
用于新行。textarea上没有name=
属性,这意味着在提交表单时无法从$\u POST
变量获取该属性。此外,您如何/在何处跟踪用户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);
}