How to pass variables to mpdf? - variables

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

Related

Laravel not inserting into table

Basically I need to have a e-mail verification system. For clarity, I will post only needed chunks of code that have impact whatsoever. When user registers, a random 40 string token is generated and sent to them, that code is appended to the route like this:
Route::get('/user/verify/{token}', 'RegisterController#verifyUser');
So when user clicks on that link supposedly route should call this:
RegisterController:
public function verifyUser($token){
$verifyUser = new VerifyUser();
$verifyUser->token = $token;
$verifyUser->getByToken();
$user = new User();
$user->id = $verifyUser->user_id;
$user->get();
if(isset($verifyUser)){
if(!$user->verified){
$user->updateVerifiedStatus();
$status = "Uspešno ste verifikovali e-mail adresu. Sada se možete ulogovati";
} else{
$status = "Već ste se verifikovali.";
}
} else{
return redirect('/')->with('error', "Vaš e-mail ne postoji");
}
return redirect('/')->with('status', $status);
}
verify_user is table which has an id of the user, and the token field, and if user is not registered, there will be no instance of that user in the table, therefore -> if(isset($verifyUser)),
also, user table has an 'verified' field, which is a boolean and stores true and false values, therefore -> if(!$user->verified).
And here are models which are used in the above mentioned controller
VerifyUser:
class VerifyUser
{
public $user_id;
public $token;
public $created_at;
public $updated_at;
public function getByToken()
{
$result =
DB::table('verify_users')
->select('*')
->where('token', $this->token)
->first();
return $result;
}
public function create()
{
$result =
DB::table('verify_users')
->insert([
'user_id' => $this->user_id,
'token' => $this->token,
]);
return $result;
}
}
User
class User
{
public function get()
{
$result =
DB::table('users')
->select('*')
->where('id', $this->id)
->first();
return $result;
}
public function updateVerifiedStatus()
{
$data = [
'verified' => true,
];
$result =
DB::table('users')
->where('id', $this->id)
->update($data);
return $result;
}
}
So, when I click the link, everything passess, I get the success status, which tells me that $user->updateVerifiedStatus() funct is returned succesfully. But, when I check the table, the field is still false, and is not updated. Any ideas?

How to execute query in phalcon model

iam using phalcon, I tried to execute query from controller, query run my model
<?php
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Query;
class CakupanBu extends Phalcon\Mvc\Model
{
public static function getJenisBU()
{
header("Access-Control-Allow-Origin: *");
header('Content-type:application/json;charset=utf-8');
$data = array();
$query = new Query(
'SELECT id_jenis_bu,count(jumlah_bu) as jumlah FROM CakupanBu group by id_jenis_bu',
$this->getDI()
);
// Execute the query returning a result if any
$jbus = $query->execute();
foreach ($jbus as $jbu) {
$data[] = array(
'id_jenis' => $jbu->id_jenis_bu,
'jumlah' => $jbu->jumlah,
);
}
return json_encode($data);
}
}
But sadly this is not working, and I ended up with an error.
<b>Fatal error</b>: Uncaught Error: Using $this when not in object context in 'CakupanBU.php:14'
from controller i call :
$jbus=CakupanBU::getJenisBU();
Could anyone give me solution? thanks you
Your function is static, so there is no $this.
To get the DI, you would replace your $this->getDI() with \Phalcon\DI::getDefault()

how to like value to %field_value% in sql or codeigniter?

I have a table named uri_table that contain:
id, uri_segment
1, /dir_name/bla-bla-1/
2, /dir_name/bla-bla-2/
3, /dir_name/bla-bla-3/
I want to get the pure link that only contain until controller_name and the controller param are not included. but when I use $_SERVER['URI_SEGMENT'] it will get the controller param too.
so I can't do this code below to search in my model:
function check_uri()
{
$this->db->like('uri_segment',$uri_segment,'after');
$id = $this->db->get('uri_table')->row_array()['id'];
return $id;
}
instead of:
function check_uri($request_uri=$_SERVER['URI_SEGMENT'])
{
//trim controller param that is numeric
for($i = strlen($request_uri)-1;$i > 0;$i--)
{
if(is_numeric($request_uri[$i]) || $request_uri[$i]=='/')
{
continue;
}
else
{
$request_uri = substr($request_uri,0,$i+1);
break;
}
}
$this->db->where('uri_segment',$request_uri);
$id = $this->db->get('uri_table')->row_array()['id'];
return $id;
}
This is my code right now but is also can remove param that is number if the $request_uri = '/dir_name/bla-bla-3/1/some_param/3' it'll return $id null. What can I do to remove the param/get uri without controller param or how to compare the $uri_segment to uri_segment ($this->db->like($uri_segment, '%uri_segment%'))?
Do one thing when you create a controller in that store the controller name like this:
class About extends CI_Controller {
// MVC config
var $PANEL = '';
var $CONTROLLER = 'about';
var $MODEL = 'mdl_about';
var $TITLE = 'page title';
var $LIST_PAGE_NAME = 'aboutus';
function About() {
parent::__construct();
//$this->load->model($this->MODEL, 'model');
}
function index() {
$this->load->view($this->LIST_PAGE_NAME);
}
}
So that above controller, model, page title and view page can be use anywhere is related to that controller.
To display the variable value use like this:
echo $this->CONTROLLER;
Or you can try this:
$this->router->fetch_class(); //for controller
$this->router->fetch_method(); //for method

Laravel 4.2 auth:attempt fails

I can't find this website and I can't figure out what is wrong with my code.
I am trying to get true for var_dump(Auth::attempt()), but it is always false.
This is my controllers method:
public function vartotojoPrisijungimoForma(){
$view = View::make('vartotojai.vartotojoPrisijungimoForma',
array('title'=>'Vartotojo Prisijungimas'));
var_dump(Auth::attempt(array('vardas'=>'aaaaa','pw'=>'aaaaa')));
return $view;
}
In my database the username is stored as vardas and password as pw
My auth.php file looks like this:
<?php
return array(
'driver' => 'eloquent',
'model' => 'Vartotojai',
'table' => 'vartotojai',
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
And the model file which is Vartotojai.php, looks like this:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Vartotojai extends ModeliuBaze implements UserInterface, RemindableInterface{
protected $table = 'vartotojai';
public $timestamps = false;
protected static $rules = array(
'vardas'=>'required|unique:vartotojai|min:4|regex:/[a-zA-Z]$/',
'pw'=>'required|alpha_num|between:4,8|confirmed',
'pw_confirmation'=>'required|alpha_num|between:4,8'
);
protected static $messages = array(
'required' => ':attribute laukelis tuscias!',
'min'=> ':attribute laukelyje galimas minimalus(:min) simboliu kiekis!',
'between' => ':attribute laukelis gali buti nuo :min - :max simboliu intervale!',
'vardas.regex'=> ':attribute turi atitikti siuos simbolius (a-zA-Z)',
'unique'=> 'Jau vartotojas su tokiu vardu uzregistruotas!',
'alpha_num'=>':attribute laukelyje galima rasyti tik skaicius ir raides!',
'confirmed'=>'Nesutampa slaptazodziai!'
);
protected $hidden = array('password');
public function getAuthIdentifier(){
return $this->getKey();
}
public function getAuthPassword(){
return $this->password;
}
public function getRememberToken(){
return $this->remember_token;
}
public function setRememberToken($value){
$this->remember_token = $value;
}
public function getRememberTokenName(){
return 'remember_token';
}
public function getReminderEmail(){
return $this->email;
}
}
I tried to check Hash:
public function vartotojoPrisijungimoForma(){
$view = View::make('vartotojai.vartotojoPrisijungimoForma',
array('title'=>'Vartotojo Prisijungimas'));
$pw = Vartotojai::find('5');
var_dump(Auth::attempt(array('vardas'=>'aaaaa','pw'=>'aaaaa')));
var_dump(Hash::check('aaaaa',$pw->pw));
return $view;
}
And hash check shows true.
You either need to change your password field from 'pw' to 'password' in your database. Laravel validates the credentials with 'password'.
OR
You could change this function to:
public function getAuthPassword(){
return $this->pw;
}
Then your attempt function should be:
var_dump(Auth::attempt(array('vardas'=>'aaaaa','password'=>'aaaaa')));

PDO return $row from a class method

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