I am trying to verify whether the method in my class is returning a true value. Please look at my object below the class and tell me if it is a valid statement. I am using this to verify whether an email address already exists in the database.
My class and it's constructor
class CheckEmail {
public function __construct($email) {
$db = Database::GetHandler();
$sql = "SELECT email from users WHERE email='$email'";
$stmt = $db->prepare($sql);
$stmt->execute();
$rows = $stmt->rowCount();
if($rows > 0) {
return true;
} else {
return false;
}
}
}
My object from this class:
if($checkEmail = new CheckEmail($_POST[email])==true) {...
Constructors cannot return a value, that doesn't make any sense. Constructors are there to create (and return) an object of its class.
You should make another function to do this check, and then call that.
class CheckEmail {
public function check($email) {
$db = Database::GetHandler();
$sql = "SELECT email from users WHERE email='$email'";
$stmt = $db->prepare($sql);
$stmt->execute();
$rows = $stmt->rowCount();
if($rows > 0) {
return true;
}
else {
return false;
}
}
}
(P.S. You can just do return $rows > 0;)
And then you can call it like this:
var $email = new CheckEmail;
if($email->check($_POST[email]) === TRUE){
// or just if($email->check($_POST[email])){
Thing is, do you really need a class here? You could just declare the CheckEmail function normally, and not in its own class.
Constructors do not return a value. You need a different approach.
http://www.php.net/manual/en/language.oop5.decon.php
Try putting
$checkEmail = new CheckEmail($_POST[email]);
Before the if statement, then
If($checkEmail) {...
Related
could use help with a simple code with both PHP and SQL (PDO) :)
Trying to access a table, withdraw 1 row from 1 column with specific details using MVC and then verifying said info, building it and then entering that info into Session storage so that I can validate what "role" and "user" is present at a certain time.
That's my controller
<?php
class PagesController {
public function home() {
$first_name = 'Qwerty';
$last_name = 'Qwerty';
require_once('views/pages/home.php');
}
public $admin_model;
public function __construct() {
$this->admin_model = new Admin();
}
public function login() {
session_start();
$log = $this->admin_model->LoginModel();
if($log == true){
$admin= $this->admin_model->findAdmin($_POST['user'],$_POST['pass']);
if($admin == true){
$_SESSION['user'] = $admin['user'];
print_r($_SESSION);
}
require_once('views/pages/login.php');
}else if($log == false){
echo "There is no existing account with that information. Please try a different account.";
require_once('views/pages/home.php');
}
}
?>
And this is my Admin Model.
<?php
require_once 'connection.php';
class Admin{
public $name;
public $role;
public $phone;
public $email;
public $password;
public $img;
public $id;
public function __construct() {
}
public function LoginModel(){
if(isset($_POST['user'])&&($_POST['pass'])){
$name= $_POST['user'];
$password=$_POST['pass'];
}
else{
$name='NULL#NULL';
$password='NULL';
}
$db = Db::getInstance();
$sql = $db->prepare('SELECT * FROM `admin` WHERE "Name" = "'.$name.'" AND Password = ' . $password .' ');
$sql->execute();
$result = $sql->setFetchMode(PDO::FETCH_ASSOC);
if($result >= 1){
return true;
}else{
return false;
}
}
public function findAdmin($name, $password){
$db = Db::getInstance();
$sql = $db->prepare('SELECT * FROM `admin` WHERE "Name" = "'.$name.'" AND Password = ' . $password .' ');
$sql->execute();
$result = $sql->setFetchMode(PDO::FETCH_ASSOC);
if($result > 0){
return $result;
}
}
}
Now, the first one, the Login() model works, BUT it doesn't matter what $_POST['user'] or $_POST['pass'] I input it always works :/... so it seems my SQL query always returns a true (i'm inputting the same into as found in the table, username "admin" and password "12345" but no matter what information I put in? it works. which is odd..
Second of all I want to "Find" the admin after login in and putting that info into a session that I can verify on every view... any help?...
I think your specific problem is that you're using the return of setFetchMode() as an indicator of whether or not rows were found by the execution. Since its return value is TRUE simply by virtue of it succeeding in setting the fetch mode, you're probably always going to see TRUE returned.
You probably need to do fetchAll() and count the records in the array, if all you want to do as verify that at least one row was returned.
I am wondering if someone could help me. I am new to PHP OOP and would like some guidance with using objects.
I am making a login script and the functions I mention below are all from the class file.
Class USER{
public function userLogin($username,$password)
{
$statusY = "Y";
$stmt = $this->connection->prepare("SELECT * FROM tbl_users WHERE user_name=:userName LIMIT 1");
$stmt ->execute(array(":userName"=>$username));
$row = $stmt ->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
$this->_user = $row; // Assign user details
$_SESSION['userSession'] = $row['user_id'];
}
}
public function getUser()
{
return $this->_user;
}
Ok so I have the getUser() function and then assign $this->_user = $row so I can retrieve the user info from the database. Now I want to acheive a couple of things from this but not sure how to go about it.
How would I go about calling $row['user_id'] in another function within the same class?
So basically
public function test()
{
$user_id = $this->_user(user_id);
$username = $this->_user(username);
}
How would I do this correctly?
Also if I want to call the information in a page such as the User Homepage.
$user_home = new USER();
$userID = $user_home->getUser(user_id);
echo $userID;
If anyone could give me some guidance as to how I can move forward with this I would greatly appreciate it. Thanks
Let's start with a basic statement regarding method and class naming: I wouldn't repeat the class' topic over and over again (in the above case "user"), instead just remove it from the method name:
class User
{
private $info= array();
private $authenticated= FALSE;
public function login ($username, $password)
{
// do your stuff
...
// set in case that user name and password have been found
$this->info= $row;
$this->authenticated= TRUE;
}
public function isAuthenticated ()
{
return $this->authenticated;
}
/**
* returns all info from a given user
*/
public function get ()
{
return $this->info;
}
/**
* returns a single field
*/
public function getField ($fieldName) {
if (isset($this->info[$fieldName]) {
return $this->info[$fieldName];
} else {
return FALSE;
}
}
}
Use the getField(FIELD) method to return only a single element of the user's row and get() to return all values.
$user= new User();
$user->login ($username, $password);
if ($user->isAuthenticated()) {
$home= $user->getField('home');
print sprintf('%s\'s home is %s', $username, $home);
}
It's also advisable to create a class for the user database table (i.e. class UserModel) and another one handling user functions (i.e. class UserAuth) which uses the UserModel class. This makes exchanging the underlying authentication source more easy.
Class USER
{
public $_user;
public function userLogin($username,$password)
{
$statusY = "Y";
$stmt = $this->connection->prepare("SELECT * FROM tbl_users WHERE user_name=:userName LIMIT 1");
$stmt ->execute(array(":userName"=>$username));
$row = $stmt ->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
$this->_user = $row; // Assign user details
$_SESSION['userSession'] = $row['user_id'];
}
}
public function getUser()
{
return $this->_user;
}
}
I use codeigniter mvc for my project, im making a unique id logger that if there id exist it will call the unique generator function again. how to call the function inside model
heres my model:
function getGenLogsId() {
$matches = '12345';
$sql = "SELECT * FROM tbllogs WHERE logsid LIKE '%".$this->db->escape_like_str($matches)."%'";
$q = $this->db->query($sql);
if($q->num_rows() > 0) {
// call function again
} else {
// if not exist save!!
}
}
you can call $this->getGenLogsId();
function getGenLogsId() {
$matches = '12345';
$sql = "SELECT * FROM tbllogs WHERE logsid LIKE '%".$this->db->escape_like_str($matches)."%'";
$q = $this->db->query($sql);
if($q->num_rows() > 0) {
$this->getGenLogsId();
} else {
// if not exist save!!
}
}
if it's in the same controller use :
$this->function();
if it's in the model:
$this->load->model('ModelName');
$this->ModelName->function();
NOTE
if it's in the controller it's a good practice to make it a private function so no direct call is allowed to that function by starting the function name with _
Example:
function _test(){
}
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.
I have seen these codes:
$result = $db->result($query);
$rows = $result->fetchAll();
how can I do similar effect? ($result contains methods?)
I think this is what you are looking for:
<?php
class test{
private $value = 0;
function foo(){
$this->value = 1;
return $this;
}
function bar(){
$this->value = 2;
echo $this->value;
}
}
$test = new test();
$result = $test->foo();
$result->bar();
?>
By having the method return itself, you can chain them together in this fashion.
Strictly speaking, you're asking about OOP in PHP, in which case, this is a reasonable example:
class HasResultMethod
{
public function result( $query )
{
return new HasFetchAllMethod();
}
}
class HasFetchAllMethod
{
public function fetchAll(){}
}
// you have a variable with a result method that has one parameter.
$result = $db->result($query);
// that returns an object which has a fetchAll method.
$rows = $result->fetchAll();
You probably are dealing with some wrapper around PDO, a library to interface with databases. Their query methods will return a PDOStatement which has methods which will allow you to get results from the DB. result is either a typo, or it behaves in a very similar way.
I got it already. What a great hint Headspin
http://sandbox.phpcode.eu/g/147bd.php
<?php
class foo{
function bar(){
return $this;
}
function fetch(){
echo "yeah";
}
}
$foo = new foo();
$result = $foo->bar();
$result->fetch();
That is easy
$db is instance of class that returnes class, so when you say
$db->result($query);
$db will return object
e.g.
//this method is inside $db class
function result($query)
{
$result = new Result();
$result->rows = mysql_query...
return $result;
}
and when you say
$result->fetchAll();
that is method inside class Result that will fetch all rows saved inside $result->rows;
e.g.
//method inside Result class
function fetchAll()
{
//fetch rows inside variable $this->rows
}
So basically what you can do with ORM (object relational mapping), you can return Array of objects, each object will represent one record from db
e.g.
Class User
{
var $ID;
var $Name;
var $LastName;
var $Email;
function load($row)
{
$this->ID = $row["ID"];
... etc
}
function save()
{
$sql = "update tbl_users set Name=:Name, LastName=:LastName, Email=:Email where ID=:ID";
//then execute your query
}
}
so how to get list of objects, its easy
select all records and add them into array
$ar = new Array();
for($i = 0; $i < count($rows); $i++)
{
$r = new User();
$r->load($rows[$i]);
}
return $ar;
simple as that...