Codeigniter result_array() returning one row - sql

In my table I have two rows but when I print_r the $data that this model function is connected to it is only returning the second row in the db why?
Model Function:
function getAllUsers()
{
$query = $this->db->get('users');
foreach($query->result_array() as $row)
{
$row['id'];
$row['fName'];
$row['lName'];
$row['email'];
$row['password'];
}
return $row;
}

Because $row is the loop variable, it will only hold the data from the last iteration after the loop has exited.
Do it like this:
function getAllUsers()
{
$rows = array(); //will hold all results
$query = $this->db->get('users');
foreach($query->result_array() as $row)
{
$rows[] = $row; //add the fetched result to the result array;
}
return $rows; // returning rows, not row
}
In your controller:
$data['users'] = $this->yourModel->getAllUsers();
$this->load->view('yourView',$data);
In your view
//in your view, $users is an array. Iterate over it
<?php foreach($users as $user) : ?>
<p> Your first name is <?= $user['fName'] ?> </p>
<?php endforeach; ?>

Related

How to pass variables to mpdf?

I want to pass variables $name and $age from my controller to mpdf view page.
However, it gives me an error: Undefined variable: name.
I tried to pass data in three ways:
1) Created separate methods in Controller getName() and getAge() and call them in a view
2) Send the variables while rendering the page
3) trying to query the age and name from Database directly from view.
All three ways didn't give result. 1 and 3 leads to not loaded page and the second one shows Undefined variable: name error.
View:
<div><?= $name; ?></div>
P.S. I also tried to do like:
<div><?echo $name; ?></div>
<div><?php $name; ?></div>
Controller:
public function actionIndex(){
$this->actionCreateMPDF();
$a = Profile::find('age')->where(['user_id'=>\Yii::$app->user->id])->asArray()->one();
$age = $a['age'];
$n = Profile::find('name')->where(['user_id'=>\Yii::$app->user->id])->asArray()->one();
$name = $n['name'];
return $this->render('index',[
'age' => $age,
'name' => $name,
]);
}
public function actionCreateMPDF(){
$b = true;
$mpdf = new mPDF();
$mpdf->WriteHTML($this->renderPartial('index'));
$mpdf->showImageErrors = true;
$mpdf->Output();
exit;
}
If anyone knows what is my problem please help me :3
Need to pass variables to function actionCreatePdf()
public function actionIndex(){
$profileData = Profile::find()
->select(['age', 'name'])
->where(['user_id'=>\Yii::$app->user->id])
->one();
$age = $profileData->age;
$name = $profileData->name;
$this->actionCreateMPDF($age, $name);
return $this->render('index',[
'age' => $age,
'name' => $name,
]);
}
public function actionCreateMPDF($age, $name){
$b = true;
$content = $this->renderPartial('index',[
'age' => $age,
'name' => $name,
]);
$mpdf = new mPDF();
$mpdf->WriteHTML($content);
$mpdf->showImageErrors = true;
$mpdf->Output();
exit;
}

simple oophp function not working

I'm new to oop and MVC and I'm trying to test the flow between my index, controller, and model files. All of the test functions work except for 'check status'. What's the problem? The function is highlighted in BOLD. (INDEX)
$Controller = new Controller;
$Controller->ShowRegisterLogin();
?> (CONTROLLER)
Class Controller {
function ShowRegisterLogin() {
echo 'ShowRegisterLogin Function works';
$Model = new Model;
$Model->TestModel();
**$Model->checkStatus();**
}
}
?>
(MODEL)
class Model {
Var $Status = 'return works';
function TestModel() {
echo 'Test Model Works';
}
**function checkStatus() {
return $this->Status;
}**
}
?>
You need to echo the value if you want to see it
echo $Model->checkStatus();
Otherwise, nothing gets done with the return value and it disappears.

registration form using Yii framework

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

Return value from external action in Yii

How to pass a value from external action in Yii to it's parent controller?
for example:
External action looks like:
<?php
class uploadAction extends CAction
{
/**
* Runs the action.
* This method is invoked by the controller owning this action.
*/
public function run()
{
.....
$fileName=$result['filename'];//GETTING FILE NAME
$this->controller->image = $fileName; // this line does not work!!
}
}
when I try to get the value of images in the parent controller, nothing return!! Any help I will appreciate.
Update:
I am using an extension to upload a file .. eajaxupload .
There is a long form.. have many fields, one of them is image. I want to upload that image by Ajax before submiting the whole form. Of course after user click on create button.. the controller must take all fields plus image name to store in the db.
The view ..
<div class="elem">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array('class'=>'inputbox grid-11-12','maxlength'=>45)); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="elem">
<?php echo $form->labelEx($model,'password1'); ?>
<?php echo $form->passwordField($model,'password1',array('class'=>'inputbox grid-11-12')); ?>
<?php echo $form->error($model,'password1'); ?>
</div>
<div class="elem">
<?php echo $form->labelEx($model,'password2'); ?>
<?php echo $form->passwordField($model,'password2',array('class'=>'inputbox grid-11-12')); ?>
<?php echo $form->error($model,'password2'); ?>
</div>
<div class="elem">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('class'=>'inputbox grid-11-12','maxlength'=>45)); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="elem">
<label for="content">User Image:</label>
<?php $this->widget('ext.EAjaxUpload.EAjaxUpload',
array(
'id'=>'uploadFile',
'config'=>array(
'action'=>Yii::app()->request->baseUrl .'/backend.php/user/upload',
'allowedExtensions'=>array("jpg"),//array("jpg","jpeg","gif","exe","mov" and etc...
'sizeLimit'=>3*1024*1024,// maximum file size in bytes
'minSizeLimit'=>50*1024,// minimum file size in bytes
'multiple'=>false,
//'onComplete'=>Yii::app()->request->baseUrl .'/backend.php/user/saveStuff/?fn='. "js:function(id, fileName, responseJSON){ alert(fileName); }",
//'messages'=>array(
// 'typeError'=>"{file} has invalid extension. Only {extensions} are allowed.",
// 'sizeError'=>"{file} is too large, maximum file size is {sizeLimit}.",
// 'minSizeError'=>"{file} is too small, minimum file size is {minSizeLimit}.",
// 'emptyError'=>"{file} is empty, please select files again without it.",
// 'onLeave'=>"The files are being uploaded, if you leave now the upload will be cancelled."
// ),
//'showMessage'=>"js:function(message){ alert(message); }"
)
)); ?>
</div>
This is the controller ..
<?php
class UserController extends Controller
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column1';
public $image;
.......
public function actions()
{
return array(
'upload' => array(
'class' => 'ext.actions.uploadAction',
),
);
}
........
public function actionCreate()
{
$model=new User;
$profile=new UserProfile;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
$profile->attributes=$_POST['UserProfile'];
if(!$this->saveUser($model, $profile))
Yii::app()->user->setFlash('error', 'Not Saved :)!');
}
$this->render('create',array(
'model'=>$model,
'profile'=>$profile,
));
}
public function saveUser($model, $profile)
{
$userValid = $model->validate();
$profileValid = $profile->validate();
$valid = $userValid && $profileValid;
if($valid)
{
$model->save(false);
$profile->user_id = $model->id;
$profile->image = !is_null($this->image)? $this->image : null; // name of image file which uploaded
$profile->save(false);
Yii::app()->user->setFlash('success', 'Saved :)!');
$this->redirect(array('index'));
return true;
}
return false;
}
}
the external action in details is:
<?php
class uploadAction extends CAction
{
/**
* Runs the action.
* This method is invoked by the controller owning this action.
*/
public function run()
{
Yii::import("ext.EAjaxUpload.qqFileUploader");
// make the directory to store the pic:
$folder=Yii::getPathOfAlias('webroot') .'/images/' . $this->controller->id . '/';// folder for uploaded files
if(!is_dir($folder))
{
mkdir($folder);
chmod($folder, 0755);
// the default implementation makes it under 777 permission, which you could possibly change
//recursively before deployment, but here's less of a headache in case you don't
}
$allowedExtensions = array("jpg");//array("jpg","jpeg","gif","exe","mov" and etc...
$sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload($folder);
$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
$fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
$fileName=$result['filename'];//GETTING FILE NAME
$this->controller->image = $fileName; // ??????
echo $return;// it's array
}
}
do this:
$this->controller->image = $fileName; // this line does not work!!
$this->controller->renderText($this->controller->image);
I bet this will display the $fileName.
Where do you try to access the controllers image property?
Values are not preserved between requests.
I've done something similar to this using a callback.
So in my controller actions() configuration I have a line:
'onSuccessCallback' => 'myCallback'
In my action class, at the end of run() I have:
call_user_func( array($this->getController(),$this->onSuccessCallback), $fileName);
In the controller I have
function myCallback($fileName)
{
this->image = $fileName;
}
I can then access the property from the controller via
$this->image

Mysterious duplicate entries in SQLite table when using INSERT

Before I used PDO and it worked fine but I had problems with inserting pictures. Now I switched to SQLite3 and the pictures are now stored correctly. But I'm experiencing a strange problem with SQLite3. Every INSERT INTO command is done twice. And this only concerns INSERT, because I had no problems with UPDATE or DELETE.
This is my test script
<?php
require_once('class.DatabaseQuery.php');
$db = new DatabaseQuery();
$sql = 'INSERT INTO Bezeichnungen(Bezeichnung_de,Bezeichnung_en,Bezeichnung_it) values("test","test","test");';
$result = $db->ExecuteQuery($sql);
echo "<pre>";
print_r($result);
echo "</pre>";
?>
This is my database class:
<?php
class DatabaseQuery {
private $_handle;
public function ExecuteQuery($sql, $params = array())
{
echo $sql;
echo "<strong>execute Query params</strong><pre>";
print_r ($params);
echo "</pre>";
echo count($params);
// make new connection if not available
if($this->_handle == null)
$this->Connect();
// make prepared statement
$query = $this->_handle->prepare($sql);
// add values to prepared statement depending on type
foreach($params as $key => $value)
{
if(is_int($value)){
$query->bindValue(':'.$key, $value, SQLITE3_INTEGER);
}else if(is_null($value)){
$query->bindValue(':'.$key, $value, SQLITE3_NULL);
}else if(strpos($value, "home/www/") !== false){
$value=file_get_contents($value);
$query->bindValue(':'.$key, $value, SQLITE3_BLOB);
$value="X'" . strtoupper(bin2hex($value));
}else{
$query->bindValue(':'.$key, $value, SQLITE3_TEXT);
}
}
$result = $query->execute();
// get all results
while($row = $result->fetchArray(SQLITE3_ASSOC)){
$res[] = $row;
}
//var_dump($x);
return $res;
}
public function Connect()
{
$this->_handle = new SQLite3("database.db");
}
public function Disconnect()
{
// close database connection
$this->_handle->close();
}
}
?>
And this is the create statement of my table
CREATE TABLE Bezeichnungen
(
_id INTEGER PRIMARY KEY,
Bezeichnung_de TEXT,
Bezeichnung_en TEXT,
Bezeichnung_it TEXT
)
Either I'm using SQLite3 the wrong way or the used library has a bug.
I'm using PHP 5.3.9, SQLite3 module version 0.7-dev and SQLite Library 3.7.7.1.
Perhaps someone can test my code on his plattform and tells me if he has the same problem.