I am having issues getting the SteamID and vac added to the database everything else is working just can not get these two. Here is my code. The connection information to the database is within the config.php I am not having any problems connecting just inserting correctly. Matter if fact it does not insert at all right now.
<?php
require 'config/config.php';
class SteamProfile{
const STEAMAPI_URL_MASK = 'http://steamcommunity.com/profiles/%s/?xml=1';
const UNKONWN_NAME_MASK = 'User #%s (Username Not Found)';
private $steamId;
private $xml;
public function __construct($steamId){
$this->steamId = $steamId;
}
public function getUsername(){
$xml = $this->getXml($this->steamId);
return $xml->steamID ? (string)$xml->steamID : sprintf(self::UNKONWN_NAME_MASK, $this->steamId);
}
private function getXml($steamId){
if ($this->xml){
return $this->xml;
}
$url = sprintf(self::STEAMAPI_URL_MASK, $steamId);
if (!$xml = simplexml_load_file($url)){
throw new UnexpectedValueException(sprintf('Unable to load XML from "%s"', $url));
}
return $this->xml = $xml;
}
public function getVAC(){
$xml = $this->getXml($this->steamId);
return $xml->vacBanned;
}
public function __toString(){
return sprintf("%s (SteamID: %s)", $this->getUsername(), $this->steamId);
}
}
if (empty($_POST)){
?>
<form name="banlist" action="index.php" method="POST">
<label for "SteamID">Steam64ID: </label><input type="text" name="SteamID"/><br />
<label for "bandate">Ban Until: </label><input type="text" name="bandate"/><br />
<button type="submit">Submit</button>
</form>
<?php
}
else{
$form = $_POST;
$SteamID = $form['SteamID'];
$profile = new SteamProfile($SteamID);
$namecheck = $profile->getUsername();
$vac = $profile->getVAC();
$bandate = $form['bandate'];
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname;",$username,$password);
$sql = "INSERT INTO PlayerBans (SteamID, playername, vac, bandate)VALUES(:SteamID, :namecheck, :vac, :bandate)";
$query = $dbh->prepare($sql);
$result = $query->execute(array(':SteamID'=>$SteamID, ':namecheck'=>$namecheck, ':vac'=>$vac, ':bandate'=>$bandate));
if ($result){
echo "Thanks for showing us this ban!";
} else {
echo "Sorry, an error occurred while editing the database. Contact the guy who built this garbage.";
}
}
?>
I have no idea what is going wrong as I am not uses to trying to use PDO
Related
I'm using EditForm and InputText to achieve data binding and forms validation. (Using <input #bind="SomeProperty" /> doesn't seem to fire component validation.)
I want to attach an event handler that gets fired whenever the value of the textbox changes:
<InputText #bind-Value="#model.ZipCode" #onkeypress="#model.InvokeThisMethod)"></InputText>
This sort of works, but when I'm in the event handler it's apparently firing before ZipCode has updated. The goal here is to do a thing when the zip code reaches 5 characters, not when the text input loses focus. I've also tried just forcing the change event to fire oninput but that just creates an error on the console about ChangedEventArgs to string not working.
How can I fire an event after the input field has updated the data binding?
After trying everything under the sun to get the grid to reload via the search string after inserting a new record, and failing, I found that I can just reload the grid by setting the search string to empty and displaying all the results (simply having a value in the search box prevents the grid from refreshing after an insert - there is no solution I could get to work for this), but at least it shows the record as being inserted. While this isn't the answer I was looking for, it will suffice for now.
Here's the index.razor page (final):
#page "/"
#inject IConfiguration config
#inject DialogService dialog
#inject NotificationService notification
<PageTitle>Memo Master</PageTitle>
<RadzenButton Click="() => GetMemos()" Text="Get Memos" ButtonStyle="ButtonStyle.Primary" ButtonType="ButtonType.Submit" />
<RadzenTextBox #ref="searchBox" Name="SearchPhrase" #bind-Value="#SearchString" MaxLength="400" #oninput="#(args => SearchString = args.Value?.ToString())" #onkeydown="#Enter" />
<RadzenButton Click="() => OpenMemo(0)" Text="New Memo" Icon="add_circle_outline" ButtonStyle="ButtonStyle.Secondary" />
<br />
<br />
#if (FoundMemos != null && !busy)
{
<RadzenDataGrid #ref=this.grid Data="#FoundMemos" TItem="MemoSearch" AllowFiltering="true" AllowSorting="true" AllowColumnResize="true" AllowPaging="true" PageSize=20
FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive" SelectionMode="DataGridSelectionMode.Single" #bind-Value="#SelectedMemos" RowClick="#OnRowClicked">
<Columns>
<RadzenDataGridColumn TItem="MemoSearch" Title="Index" Width="70px" Filterable="false" TextAlign="TextAlign.Left">
<Template Context="m">
<RadzenText TextStyle="TextStyle.Caption">#m.Idx.ToString()</RadzenText>
</Template>
</RadzenDataGridColumn>
<RadzenDataGridColumn TItem="MemoSearch" Property="Title" Title="Title">
</RadzenDataGridColumn>
<RadzenDataGridColumn TItem="MemoSearch" Title="Modified" Width="140px" TextAlign="TextAlign.Right">
<Template Context="m">
<RadzenText TextStyle="TextStyle.Caption">#m.ModifiedOn.ToString("MM/dd/yyyy hh:mm tt")</RadzenText>
</Template>
</RadzenDataGridColumn>
</Columns>
</RadzenDataGrid>
}
else
{
<DisplaySpinner />
}
<br />
<br />
<RadzenButton Click="Reset" Text="Reset" ButtonStyle="ButtonStyle.Secondary" />
#code {
[Parameter]
public string? SearchString { get; set; }
List<MemoSearch> FoundMemos = new();
private string DBConnStr { get; set; } = "";
public DB dB = new();
IList<MemoSearch>? SelectedMemos;
RadzenTextBox? searchBox;
private bool busy;
private RadzenDataGrid<MemoSearch>? grid; //reference to grid, so forced reloading can happen - though it doesn't actually work
async Task OpenMemo(int Idx)
{
string DialogTitle = (Idx == 0) ? "Create New Memo" : $"Edit Memo {Idx.xToStr()}";
object? RefreshResults = await dialog.OpenAsync<MemoDetails>(DialogTitle, new Dictionary<string, object>() { { "Idx", Idx } });
RefreshResults = (RefreshResults == null) ? false : RefreshResults;
if (RefreshResults.xToBoo())
{
if (Idx == 0) SearchString = ""; //force setting to empty reloads grid but only w/o search entry
await GetMemos();
}
await ReturnFocus();
}
protected override async Task OnInitializedAsync()
{
dB.DBConnStr = await Task<string>.Run(()=> config.GetConnectionString("DBConnStr"));
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender) await ReturnFocus(); //NOTE: this is for Radzen "elements"
}
public async Task GetMemos()
{
busy = true;
FoundMemos = await dB.MemoSearchByPageFilterSortAsync(SearchString, PageSize: 9999);
busy = false;
}
public async Task Reset()
{
FoundMemos = new();
SearchString = "";
await ReturnFocus();
}
public async void Enter(KeyboardEventArgs e)
{
if (e.Code == "Enter" || e.Code == "NumpadEnter" || e.Key == "Enter")
{
await GetMemos();
StateHasChanged(); //need to call this here after keypress, lest you get a continual spinner
}
}
async Task OnRowClicked(Radzen.DataGridRowMouseEventArgs<MemoSearch> args)
{
if (args != null)
{
await OpenMemo(args.Data.Idx);
}
}
async Task ReturnFocus()
{
if (searchBox != null) await searchBox.Element.FocusAsync();
}
}
and the MemoDetails.razor page:
#inject IConfiguration config
#inject DialogService dialog
#inject NotificationService notification
#if (memo != null)
{
<RadzenTemplateForm TItem="Memo" Data=#memo Submit=#OnSubmit>
<p>
<RadzenLabel Component="Title" Text="Title" />
<RadzenTextBox id="MemoTitle" Name="Title" #bind-Value=#memo.Title MaxLength="400" />
<RadzenRequiredValidator Component="Title" Text="Title is required!" />
</p>
<p>
<RadzenLabel Component="Body" Text="Memo" />
<RadzenTextArea id="MemoBody" Name="Body" #bind-Value=#memo.Body Rows="18" />
</p>
<p>
<RadzenLabel Component="Keywords" Text="Key Words" />
<RadzenTextBox id="MemoKeywords" Name="Keywords" #bind-Value=#memo.Keywords MaxLength="400" />
</p>
<RadzenButton ButtonType="ButtonType.Submit" ButtonStyle="ButtonStyle.Success" Icon="save" Text="Save" BusyText="Saving ..." IsBusy=#busy />
#if (Idx > 0)
{
<RadzenButton ButtonType="ButtonType.Button" ButtonStyle="ButtonStyle.Danger" Icon="delete" Text="Delete" Click="#((args) => DeleteMemo(memo.Idx))" #onclick:stopPropagation="true"></RadzenButton>
}
<RadzenButton Text="Close" Click="() => dialog.Close(false)" ButtonStyle="ButtonStyle.Light" />
</RadzenTemplateForm>
}
#code {
[Parameter]
public int Idx { get; set; } = 0;
public DB dB = new();
Memo? memo;
bool busy;
protected override async void OnInitialized()
{
dB.DBConnStr = config.GetConnectionString("DBConnStr");
memo = (Idx == 0) ? new Memo() : await GetMemoByIdx(Idx);
await InvokeAsync(() => StateHasChanged()).ConfigureAwait(false); //IMPORTANT!!
}
public async Task<Memo> GetMemoByIdx(int Idx) => await dB.MemoSelectByIdxAsync(Idx);
async Task OnSubmit(Memo memo)
{
int Result;
bool RefreshResults = false;
if (memo.ModifiedOn == DateTime.MinValue) memo.ModifiedOn = DateTime.Now;
string NotificationDetailMessage = memo.Idx == 0 ? "New Memo has been created." : $"Memo {memo.Idx} has been saved.";
busy = true;
Result = await dB.MemoUpsertAsync(memo);
if (Result < -1)
{
notification.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "Error Saving", Detail = "An error saving this record has occured!\n" + dB.LastErrorMsg, Duration = 4000 });
}
else
{
notification.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "Save Success", Detail = NotificationDetailMessage, Duration = 2000 });
RefreshResults = true;
}
busy = false;
dialog.Close(RefreshResults);
}
async Task DeleteMemo(int Idx)
{
int Result;
bool RefreshResults = false;
var confirmResult = await dialog.Confirm("Are you sure?", "Confirm Memo Deletion");
if (confirmResult.HasValue && confirmResult.Value)
{
busy = true;
Result = await dB.MemoDeleteByIdxAsync(Idx);
if (Result < -1)
{
notification.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "Error Deleting", Detail = "An error deleting this record has occured!\n" + dB.LastErrorMsg, Duration = 4000 });
}
else
{
notification.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "Deletion Success", Detail = $"Memo {Idx} has been deleted.", Duration = 2000 });
RefreshResults = true;
}
}
busy = false;
dialog.Close(RefreshResults);
}
}
Good enough, for now, but still baffled as to what Radzen is doing behind the scenes.
<InputText class="form-control" Value="#model.ZipCode" ValueExpression="#( ()=> model.ZipCode )" ValueChanged="#( (string s) => model.InvokeThisMethod(s) )"></InputText>
I didn't find this in the Microsoft documentation. I found it on the Telerik site for their Blazor controls (which apparently works for the non Telerik controls).
Dealing with form fields in Blazor really sucks right now.
<input #bind="model.Property" />
or
<InputText #bind-Value="model.Property" />
and then the ValueExpression attributes shown above. The intellisense in .razor files for VS2019 is poorly implemented. This sucks.
I have problem with my first module.
I create a module modules/fashion/fashion.php
<?php
class Fashion extends Module
{
function __construct()
{
$this->name = 'fashion';
$this->tab = 'administration';
$this->version = 1.0;
$this->bootstrap = true;
parent::__construct(); // The parent construct is required for translations
$this->page = basename(__FILE__, '.php');
$this->displayName = $this->l('Block Fashion');
$this->description = $this->l('Add a fashion block');
}
public function install()
{
if (!parent::install() ||
!$this->registerHook('header')) {
return false;
}
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
$tab = new Tab();
$tab->active = 1;
$tab->class_name = 'AdminFashionController';
$tab->name = array();
foreach (Language::getLanguages(true) as $lang) {
$tab->name[$lang['id_lang']] = "Fashion";
}
$tab->id_parent = (int)Tab::getIdFromClassName('Fashion');
$tab->module = $this->name;
return $tab->add();
}
public function uninstall()
{
// Uninstall Tabs
$tab = new Tab((int)Tab::getIdFromClassName('Fashion'));
$tab->delete();
// Uninstall Module
if (!parent::uninstall())
return false;
}
/**
* Returns module content
*
* #param array $params Parameters
* #return string Content
*/
}
?>
What is more i create modules/fashion/controller/admin/FashionAdminController.php
<?php
class FashionAdminController extends ModuleAdminController
{
public function initContent(){
parent::initContent();
$this->setTemplate('fashion.tpl');
}
}
?>
And modules/fashion/views/templates/admin/fashion.tpl
<!-- Block mymodule -->
<div id="mymodule_block_left" class="block">
<h4>Welcome!</h4>
<div class="block_content">
<p>Hello,
{if isset($my_module_name) && $my_module_name}
{$my_module_name}
{else}
World
{/if}
!
</p>
<ul>
<li>Click me!</li>
</ul>
</div>
</div>
<!-- /Block mymodule -->
So, when i click in my Admin Panel the link Fashion the shows "The page is no found" Why? What i did wrong? Can someone help me?
At first, check if the menu(tab) has been created in the backend or not.
I also think that the admin controller name should start with ADMIN : AdminFashionController and use this name for tab class :
$tab->class_name = 'AdminFashion';
Sample from default module:
public function installTab()
{
$tab = new Tab();
$tab->active = 1;
$tab->class_name = "AdminLinkWidget";
$tab->name = array();
foreach (Language::getLanguages(true) as $lang) {
$tab->name[$lang['id_lang']] = "Link Widget";
}
$tab->id_parent = (int)Tab::getIdFromClassName('AdminParentThemes');
$tab->module = $this->name;
return $tab->add();
}
You have to add "active" and remove "position"(is automatic)
Hey guys I am learning OOP in php. I come across some issue, when I try to customize PDO in my own class. Basically I have tried to return the row and fetch it outside my class. Unfortunately I would not work. I get this error "Call to a member function fetch() on a non-object". Have a look and give me some tips if You can. Many thanks.
$connection = new MySql(DBUSER, DBPASS);
$row = $connection->query("select * from users", "name");
while($row->fetch(PDO::FETCH_ASSOC)){
echo "<p>". $row["name"] ."</p>";
}
And here is how the MySql class look like:
class MySql{
private $dbc;
private $user;
private $pass;
function __construct($user="root", $pass=""){
$this->user = $user;
$this->pass = $pass;
try{
$this->dbc = new PDO("mysql:host=localhost; dbname=DBNAME;charset=utf8", $user, $pass);
}
catch(PDOException $e){
echo $e->getMessage();
echo "Problem z Połączeniem do MySql sprawdź haslo i uzytkownika";
}
}
public function query($query, $c1=""){
$mysqlquery = $this->dbc->prepare($query);
$mysqlquery->execute();
return $row = $mysqlquery->fetch(PDO::FETCH_ASSOC);
/* I WANT TO PERFORM COMENTED CODE OUTSIDE THE CLASS
while($row = $mysqlquery->fetch(PDO::FETCH_ASSOC)){
if($c1!=""){
echo "<p>". $row[$c1] ."</p>";
}
}
*/
}
If you want to return $mysqlquery to iterate over it, you have to return $mysqlquery, not just one row.
Here is a better version of your class, with dramatically improved error handling and security. But still awful configurability though.
class MySql{
private $dbc;
function __construct($user="root", $pass=""){
$dsn = "mysql:host=localhost; dbname=DBNAME;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$this->dbc = new PDO($dsn, $user, $pass, $opt);
}
public function query($query, $data = array()){
$stm = $this->dbc->prepare($query);
$stm->execute($data);
return $stm;
}
}
$connection = new MySql(DBUSER, DBPASS);
$stm = $connection->query("select * from users WHERE name = ?", array("name"));
while($row = $stm->fetch()){
echo "<p>". $row["name"] ."</p>";
}
I can figure out why it's not binding. So I have a form where a ListBox is in a partial view which I reload everytime I click on a checkbox to fill the listbox.
The code of my ModelView for the form is :
<div class="row-fluid">
<div class="span3">
<label>Fonction(s):</label>
</div>
<div class="span9" id="ListeFonction">
#Html.Partial("ListerFonction", Model)
</div>
</div>
<div class="row-fluid">
<div class="span5 offset3">
<div class="fonctions_container">
#foreach (extranetClient.Models.Classes.FonctionContact fonction in ViewBag.Fonctions)
{
string coche = "";
if ((#Model.ListeFonctions).Any(c => c.IdFonction == fonction.IdFonction))
{
coche = "checked";
}
<input type="checkbox" #coche class="checkbox" value="#fonction.IdFonction" />#fonction.LibelleFonction <br />
}
</div>
</div>
</div>
So as you can see, I render a partial view just after the "Email" Textbox. The code for it is :
#Html.LabelFor(contact => contact.SelectedFonctionIds, "ListeFonctions")
#Html.ListBoxFor(contact => contact.SelectedFonctionIds, new MultiSelectList(Model.ListeFonctions, "IdFonction", "LibelleFonction"), new { disabled = "disabled")
The model associated to that view looks like that:
private List<int> _selectedFonctionIds;
public List<int> SelectedFonctionIds
{
get
{
return _selectedFonctionIds ?? new List<int>();
}
set
{
_selectedFonctionIds = value;
}
}
public List<FonctionContact> ListeFonctions = new List<FonctionContact>();
public MultiSelectList ListeFonctionsSelectList
{
get
{
return new MultiSelectList(
ListeFonctions,
"IdFonction", // dataValueField
"LibelleFonction" // dataTextField
);
}
}
public Contact() { }
public Contact( List<FonctionContact> listeFonctions, List<int> selectedFonctionIds)
{
this.ListeFonctions = listeFonctions;
this.SelectedFonctionIds = selectedFonctionIds;
}
public Contact(int idContact, string nom, string prenom, string email, string telephoneFixe, string telephonePort) {
this.IdContact = idContact;
this.Nom = nom;
this.Prenom = prenom;
this.Email = email;
this.TelephoneFixe = telephoneFixe;
this.TelephonePort = telephonePort;
}
public Contact(int idContact, string nom, string prenom, List<int> selectedFonctionIds, List<FonctionContact> listeFonctions, string email, string telephoneFixe, string telephonePort)
{
this.IdContact = idContact;
this.Nom = nom;
this.Prenom = prenom;
this.SelectedFonctionIds = selectedFonctionIds;
this.ListeFonctions = listeFonctions;
this.Email = email;
this.TelephoneFixe = telephoneFixe;
this.TelephonePort = telephonePort;
}
But the ListBox of the partial view is not binding with the model. I get well the other informations but not these in the listbox. Somebody has an idea ?
Why are you forcing the ListBox's id here:
#Html.ListBoxFor(contact => contact.SelectedFonctionIds,
new MultiSelectList(Model.ListeFonctions, "IdFonction", "LibelleFonction"),
new { disabled = "disabled", **id="idFonctions"** })
ListBoxFor helper is supposed to generate the ListBox's id for you, and the Id should be the same as the attribute it should bind with. Shouldn't it be SelectedFonctionIds?
Was the binding working before you started using the PartialView? Because from your previous question, I see that you had:
#Html.ListBoxFor(contact => contact.SelectedFonctionIds, Model.ListeFonctionsSelectList, new { disabled = "disabled" })
in your View (i.e., you didn't set the id attribute).
I am new to Yii framework. I want to implement a registration form with Yii .
I check the blog project on its demo projects but it hasn't got a registration form.
Do anyone knows a tutorial about this issue?
For registration system.
You should follow the steps.
1st you make a table user/signup/register as you wish.
Now create CRUD for that so you can easily insert your data in user table.
I have a table and it have five different fields i.e. id, name, conatct_no, email, password
Now you create a folder in view named it "register".
In view you just made a file index.php and register.php
register.php is your form. which you can made.
Register.php
<h2>Registration Form</h2>
<div class="form">
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($model); ?>
<div class="row">
<?php echo CHtml::activeLabel($model,'Name'); ?>
<?php echo CHtml::activeTextField($model,'name') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Contact Number'); ?>
<?php echo CHtml::activeTextField($model,'contact_no') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'email'); ?>
<?php echo CHtml::activeTextField($model,'email') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'password'); ?>
<?php echo CHtml::activePasswordField($model,'password') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Retype Password'); ?>
<?php echo CHtml::activePasswordField($model,'retypepassword') ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('Register'); ?>
</div>
<?php echo CHtml::endForm(); ?>
</div><!-- form -->
Now you need a controller file for registration i.e. registerController.php.
registerController.php
class registerController extends Controller
{
public function actionIndex() {
$this->render('index');
}
public function actionRegister() {
$model = new RegisterForm ;
$newUser = new User;
if(isset($_POST['RegisterForm'])) {
$model->attributes = $_POST['RegisterForm'];
if($model->validate()) {
$newUser->name = $model->name ;
$newUser->contact_no = $model->contact_no;
$newUser->email = $model->email;
$newUser->password = $model->password;
if($newUser->save()) {
$this->_identity = new UserIdentity($newUser->email,$newUser->password);
if($this->_identity->authenticate())
Yii::app()->user->login($this->_identity);
$this->redirect(Yii::app()->user->returnUrl);
}
}
}
$this->render('register',array('model'=>$model));
}
}
Now you need a model file for your validation. RegisterForm.php
class RegisterForm extends CFormModel
{
public $contact_no ;
public $name ;
public $email;
public $password ;
public $retypepassword;
public function tableName()
{
return 'user';
}
public function rules() {
return array(
array('name, contact_no, email, password, retypepassword', 'required'),
array('name, email, password, retypepassword', 'length', 'max'=>200),
array('email', 'email', 'message'=>'Please insert valid Email'),
array('contact_no', 'length', 'max'=>30),
array('retypepassword', 'required', 'on'=>'Register'),
array('password', 'compare', 'compareAttribute'=>'retypepassword'),
array('id, name, contact_no, email', 'safe', 'on'=>'search'),
);
}
}
You need to also change the UserIdentity.php file in your protected/component directory.
class UserIdentity extends CUserIdentity
{
private $_id ;
public function authenticate()
{
$email = strtolower($this->username);
$user = User::model()->find('LOWER(email)=?',array($email));
if($user === null)
$this->errorCode = self::ERROR_USERNAME_INVALID ;
else if(!$user->password === $this->password)
$this->errorCode = self::ERROR_PASSWORD_INVALID ;
else {
$this->_id = $user->id ;
$this->username = $user->email ;
$this->errorCode = self::ERROR_NONE ;
}
return $this->errorCode == self::ERROR_NONE ;
return !$this->errorCode;
}
public function getId() {
return $this->_id ;
}
}
That's it.
It is a complete registration form set up, i have made it myself.
If you are first timer, then you need to understand how the controller work and how controller interact with view and model. If you are already familiar with it then you may easily can make registration system with your own.
Here is the link which help you to understand yii.
http://www.yiiframework.com/screencasts/
Thanks.
First, create a table for Users. Generate a User model and a controller based on this table using gii and adjust the code to your liking. Inside the User controller create a function to handle the registration:
function actionRegister() {
$model = new User('register');
// collect user input data
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
// validate user input and redirect to the previous page if valid
$model->setAttributes(array(
'datereg' => time(), //additional data you want to insert
'lastlogin' => time() //additional
));
if($model->save())
{
//optional
$login=new LoginForm;
$login->username = $_POST['User']['username'];
$login->password = $_POST['User']['password'];
if($login->validate() && $login->login())
$this->redirect('/pages/welcome');
}
}
else
// display the registration form
$this->render('register',array('model'=>$model));
}
You must have a valid view file (register.php)
$login=new LoginForm;
$login->username = $_POST['User']['username'];
$login->password = $_POST['User']['password'];
if($login->validate() && $login->login())
$this->redirect('/pages/welcome');
This block of code 'authenticates' the user and logs him in right after a successful registration. It uses CUserIdentity. $login->login() hashes the password.
Also, you must have something like this to process the data before it inserts it into the table
public function beforeSave() {
if(parent::beforeSave() && $this->isNewRecord) {
$this->password = md5($this->password);
}
return true;
}
Hashing the password inside the controller is also fine. However I wanna do everything DB related inside the Model class.
You may notice that I didn't call $model-validate() here. This is because $model->save() also calls the validation method. More info: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-detail
It is easy to create a form with yii using CActiveForm.
Here is a link of yii documentation :: Yii CActiveForm
You must create Registration form, using CAvtiveForm (see LoginForm for example).
Create your Users model.
Create controller:
class UsersController extends Controller
{
public function actionSignup()
{
$model = new RegistrationForm;
if (isset($_POST['RegistrationForm'])) {
if ($model->validate()) {
$user = new Users;
$user->populateRecord($form->attributes);
$user->save();
$this->redirect(Yii::app()->createUrl('/'));
}
}
$this->render('signup', array('model' => $model));
}
}