简体   繁体   English

将数据保存在cakephp数据库中

[英]save data in cakephp database

i have a cakephp web app that i'm developing. 我有一个我正在开发的cakephp Web应用程序。 I have a UsersController.php file,which handles all users registrations and logins. 我有一个UsersController.php文件,该文件处理所有用户的注册和登录。 When a user is logged in,he can use the functionality of FeaturesController.php. 当用户登录后,他可以使用FeatureController.php的功能。 The FueaturesController.php has a view file,the create.ctp . FueaturesController.php有一个视图文件create.ctp。 In create.ctp,the user inserts some data into an HTML form and these data are saved into a database,using $this->Modelname->save($this->request->data). 在create.ctp中,用户使用$ this-> Modelname-> save($ this-> request-> data)将一些数据插入HTML表单,并将这些数据保存到数据库中。

NOW,i want to add into a field of the database the username of the user that did/used that HTML,but till now i have not succeed! 现在,我想在数据库的字段中添加使用/使用过HTML的用户的用户名,但是到目前为止,我还没有成功! My code looks like this: 我的代码如下所示:

$username = $this->Session->read('Auth.User.username');

so that i save the username of the user into the variable $username. 这样我将用户的用户名保存到变量$ username中。

But now,how can i insert it into the database? 但是现在,我如何将其插入数据库? I have tried various ways but it didn't work :/ 我尝试了各种方法,但是没有用:/

Anyone's help is welcomed,thank you in advance :) 欢迎任何人的帮助,谢谢您:)

You shouldn't add the username to the form, it's not secure as a malicious user simply has to modify the HTML to change it. 您不应该将用户名添加到表单中,因为用户恶意仅需修改HTML即可对其进行更改,因此用户名并不安全。 Instead, you should set it right before saving: 相反,您应该在保存之前设置它:

$this->request->data['Modelname']['username'] = $this->Auth->user('username');
$this->Modelname->save($this->request->data);

Assuming you're using the authentication component $this->Auth->user('username'); 假设您正在使用身份验证组件$this->Auth->user('username'); is the same as $this->Session->read('Auth.User.username'); $this->Session->read('Auth.User.username'); by the way, just a bit shorter. 顺便说一下,只是短一点。

$data['modelname']['dbfieldname'] = $username;
$this->modelname->save(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM