Using PHP Activerecord Finders in Classes - php

I'm trying to test if a record exists with the following code using PHP Activerecord:
class User extends ActiveRecord\Model {
public function user_exists() {
$user = User::find_by_email($this->email);
if ( $user ) {
return true;
} else {
return false;
}
}
}
$user = new User();
$user->email = "test#email.com";
if ( $user->user_exists() ) {
echo "user exists";
} else {
echo "no user";
}
For some reason, I'm getting a 'Call to undefined method: find_by_email' error. What am I doing wrong?

Try the exists method:
User::exists(array('email' => $this->email));
Which is faster because it only checks for existence but does not fetch the data.
Or even better; use model validations:
http://www.phpactiverecord.org/projects/main/wiki/Validations#validates_uniqueness_of

Related

Store model function return to controller function

I have a model which returns a username of the person that has logged into the website to a controller. I am trying to save the username into a variable which i can user to then insert back into another table, however i am having no luck saving the data. Below is my model and controller classes.
Model:
function is_loggedin()
{
$session_id = $this->session->userdata('session_id');
$res = $this->db->get_where('logins',array('session_id' => $session_id));
if ($res->num_rows() == 1) {
$row = $res->row_array();
return $row['name'];
}
else {
return false;
}
}
Part of my Controller:
public function index()
{
$loggedin = $this->authlib->is_loggedin();
if ($loggedin === false)
$this->load->view('login_view',array('errmsg' => ''));
else
{
$this->load->view('postquestion_view',array('username' => $loggedin));
$user = $loggedin['username'];
}
}
public function askquestion()
{
$qtitle = $this->input->post('title');
$qdetails = $this->input->post('details');
$qtags = $this->input->post('tags');
$qcategory = $this->input->post('category');
$quser = $user;
Error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: user
Filename: controllers/postq.php
Line Number: 47
Here the error message is very clear. The variable $user in the last line of the function -action- askquestion() snippet is not defined. Basically, you have to read more about variables scope.
In your current situation, the code of index action should be in constructor and the variable user should be an object property. i.e it should defined globally in your controller's class and then takes its value from the constructor something like the following general demo:
<?php
class Blog extends CI_Controller {
public $user = false;
public function __construct()
{
parent::__construct();
// Your own constructor code
}
public function askquestion()
{
$qtitle = $this->input->post('title');
$qdetails = $this->input->post('details');
$qtags = $this->input->post('tags');
$qcategory = $this->input->post('category');
$quser = $this->user; //NOTICE THIS LINE
}
?>

Cannot save POST items to database with Phalcon framework

Controller:
class PeopleController extends \Phalcon\Mvc\Controller{
public function indexAction(){
}
public function CreatePersonAction(){
$person = new people();
$person->firstName=$this->request->getPost("firstName");
$person->surname=$this->request->getPost("surname");
$person->telephone=$this->request->getPost("telephone");
$person->email=$this->request->getPost("email");
$person->city=$this->request->getPost("city");
$person->country=$this->request->getPost("country");
$person->save();
if ($person) {
echo"Successfully Registered User!";
} else {
echo "Sorry, the following problems were generated: ";
foreach ($person->getMessages() as $message) {
echo $message->getMessage(), "<br/>";
}
}
}
}
Model:
<?php
class People extends \Phalcon\Mvc\Model{
}
I have tried implementing the getSource() method into the model as the phalcon docs suggest that but still not getting the desired output of saving the POST items to the database
Try this:
<?php
use Phalcon\Mvc\Controller as PhController;
class PeopleController extends PhController
{
public function IndexAction()
{
//When no view(aka template) is used you should disable the view rendering
//Otherwise the output buffer can get overwritten and your echoes won't display
$this->view->disable();
echo "<h1>Index Action!</h1>";
}
public function CreatePersonAction()
{
$this->view->disable();
if($this->request->isPost()) {
$dataSent = $this->request->getPost();
$person = new People();
$person->firstName = $dataSent["firstName"]
$person->surname = $dataSent["surname"];
$person->telephone = $dataSent["telephone"];
$person->email = $dataSent["email"];
$person->city = $dataSent["city"];
$person->country = $dataSent["country"];
$savedSuccessfully = $person->save();
if($savedSuccessfully) {
echo "Successfully Registered User!";
} else {
$messages = $person->getMessages();
echo "Sorry, the following problems were generated: ";
foreach ($messages as $message) {
echo "$message <br/>";
}
}
} else {
echo "The request method should be POST!";
}
}
}
Also, add this code to your main index.php (just before Phalcon\Mvc\Application->handle()):
$debug = new \Phalcon\Debug();
$debug->listen();
With this you'll get better error messages, so you can check if your DB settings are OK. Also remember that Phalcon only works with the database schema passively, that means, all tables and fields should already exist to the Model get stored, Phalcon just use the tables and never create them.

having trouble in codeigniter passing result or method from model to controller?

I am trying to create a basic login, no error checking or anything yet, in an effort to get used to codeigniter. Below is my controller class method that I am attempting to pass the result from my model method back in to verify username and password.
public function login()
{
if (isset($_POST['email'])) {
$this->cdata['email'] = $_POST['email'] ;
} else {
$this->cdata['email'] = "";
}
if (isset($_POST['password'])) {
$this->cdata['password'] = $_POST['password'];
} else {
$this->cdata['password'] = "";
}
$this->load->model("dbaccess");
$this->loggedin = $this->dbaccess->check_input($this->cdata['email'], $this->cdata['password']);
if($this->loggedin == TRUE) {
$this->load->view('carerview', $this->cdata);
} else {
$this->cdata['warning'] = "Check failed ! Please try again";
$this->load->view('mainview', $this->cdata);
}
}
The post from my view seems to be working fine. The post is sent back to the main login/index, to the method login (shown above) below shows my model class which is called in my login method in the controller it only has one method so far. check_input()
class Dbaccess extends CI_Model
{
function __construct()
{
parent::__construct();
}
function check_input($email, $password)
{
$this->db->select('email');
$this->db->from('tablename');
$this->db->where('email', $email);
$this->db->where('password', $password);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return TRUE;
} else {
return FALSE;
}
}
}
When I hit submit on my index page I keep getting the warning no matter what and I can't figure out where the issue is.
Try if it works:
function login()
{
if( $this->input->post( null ) ){ #check if the post array is not blank
$this->load->model("dbaccess");
$this->loggedin = $this->dbaccess->check_input($this->input->post('email'),$this->input->post('password'));
}else{
$this->loggedin = false;
}
if($this->loggedin == TRUE)
{$this->load->view('carerview',$this->cdata);}
else
{$this->cdata['warning']="Check failed ! Please try again";
$this->load->view('mainview',$this->cdata);
}
}
Is your table actually called tablename? Just to try and debug it, try this inside your check_input function and post the results (changing the username/pass if needed):
function check_input($email,$password)
{
var_dump($email);
var_dump($password);
$this->db->select('email');
$this->db->from('tablename');
$this->db->where('email', $email);
$this->db->where('password', $password);
$query = $this->db->get();
echo $this->db->last_query();
if (!$query) {
// if query returns null
$msg = $this->db->_error_message();
exit("Error: ".$msg);
}
if($query->num_rows() > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}

php function not returning class object

I have a DB class that I've created several functions in to return various values. One of the functions returns (or is supposed to) a "user" class object that represents a logged in user for the application.
class user {
public $guid = '';
public $fname = '';
public $lname = '';
public function __construct() {}
public function print_option() {
return "<option value='$this->guid'>$this->name</option>";
}
}
In the DB class I have the following 2 functions:
public function get_user($uid) {
$sql = '';
$usr = new user();
$sql = "SELECT guid, fname, lname FROM ms.users WHERE guid=?";
if($sth = $this->conn->prepare($sql)) {
$sth->bind_param('s', $uid);
if($sth->execute()) {
$sth->bind_result($usr->guid, $usr->fname, $usr->lname);
$sth->fetch();
print_r($usr); // PRINTS OUT CORRECTLY
return $usr;
}
else {return null;}
}
else {return null;}
}
public function get_practice_user_list($pguid) {
$ret = '';
$sql = "SELECT user_guid FROM ms.perm WHERE p_guid=?";
if($sth = $this->conn->prepare($sql)) {
$sth->bind_param('s', $pguid);
if($sth->execute()) {
$usr = new user();
$guid = '';
$sth->bind_result($guid);
while($sth->fetch()) {
print_r($guid); // PRINTS GUID correctly
$usr = $this->get_user($guid);
print_r($usr); // PRINTS NOTHING object is null so prints "error" two lines later.
if($usr != null) $ret .= $usr->print_option();
else print "error";
}
return $ret;
}
else {return null;}
}
else {return null;}
}
I'm just not understanding why the "user" object is not returning in this instance. Others calls to the get_user function work just fine and return the user class object pertaining to that user.
TIA
I guess you guid may be an integer so
$sth->bind_param('s', $uid);
bind_param's first param should be 'i' not 's';
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
The problem was with the query. Since the code was just looping through one query (get_practice_user_list), then calling the get_user function and attempting a second query MySQL came back with an error of out of sync message. When I looked that up, I was able to fix it by doing a fetch_all on the first query then looping through that array to get the users.

Codeigniter execute code in every controller

I'm rather new to Codeigniter, so I may be going about this the wrong way. In the header for my template, I have a spot for displaying account information or a message to log in.
In order for it to work properly, each controller obviously need to have the same code. To avoid this, the user guide says I should be able to extend CI_Controller and it automatically includes that code. However, that's not working for me. Here's what I've got.
application/core/MY_Controller.php:
<?php
class MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->model('user_model');
if ( $this->user_model->validateToken ( $this->input->cookie('session_token', TRUE) ) )
{
$data['login_info'] = 'Logged in as '. $this->user_model->getUsernameAsLink($this->input->cookie('session_token', TRUE)).'<BR />
Control Panel';
}
else
{
$data['login_info'] = 'You are not logged in<BR />
Log In';
}
}
}
?>
the model it references:
<?php
class User_model extends CI_Model {
public function __construct()
{
}
public function validateToken($token)
{
// Get token from database to check against cookie
$query = $this->db->query('SELECT `login_token` FROM `Users` WHERE `login_token` = "'.$token.'"');
// Match Found?
$rowCount = $query->num_rows();
if ( $rowCount == 1 ) {
return true;
} else {
return false;
}
}
public function getUsernameAsLink ( $token )
{
// Get token from database to check against cookie
$query = $this->db->query('SELECT `username` FROM `Users` WHERE `login_token` = "'.$token.'"');
foreach( $query->result() as $row ) {
$username = $row->username;
}
$returnString = ''.ucfirst ( $username ).'';
return $returnString;
}
}
?>
I'm getting notice errors saying that the $data['login_info'] value doesn't exist. Is there anything I've left out to keep it from processing the extension to MY_Controller?
For $data to be available in your other controllers, you need to make it available. Try setting it to $this->data and using that same thing in the other controllers.

Categories