How to pick up true or false from function - php

I am currently writing a isRegistered function. This function is written within a class called User. This is the code:
public function isRegistered($email){
$ir = $this->db->prepare('select * from users where email=?');
$ir->bindParam(1, $email);
$ir->execute();
if ($ir->rowCount()==1){
return true;
}
else { return false;}
}//end of function isRegistered
I am instantiating the class and this function on the register page, and I am trying to do this:
if(!empty($_POST['email'])){
$email = $_POST['email'];
$fp = new User();
$fp->isRegistered($email);
if($fp==1){
echo "email exists";
}
else {echo "email doesn't exist.";}
}
else echo "Please enter an email address.";
Obviously this is not working. How do I get it to work? What is the right way to do it?
I know I am returning either a true or a false from the method isRegistered. I just don't know how to pick that response up when I instantiate it.

I think you want:
if($fp->isRegistered($email)){
...
Or assign the return value of your function to $fp...

Related

How would I go about starting to convert this code into OOP PHP?

I'm trying to learn about Object Oriented Programming and I want to turn this code into such. I've got some knowledge so far from google and here and in particular http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762.
The way I understand it is I need classes that contain a certain set of instructions that can be used with universal objects outside of those classes.
My idea so far has been to set up a User class where names are stored (coming from a HTML/PHP form).
class User {
public $nameStore, $fName, $lName, $email;
public function __construct ($fName, $lName, $email) {
$this->$fN = $fName;
$this->$lN = $lName;
$this->$eN = $email;
}
Like the above^. But I'm still confused about where other instructions of my code should go. That's where I need the most help. From what I've read, it hasn't helped me get the full grasp of what I need to do. If someone could help get me started in the right direction on how to make my code into an OOP type I would greatly appreciate it. Thanks!
Below is my procedural code that I want to convert to OOP.
<?php
session_start();
$formNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grantle.com';
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User-------------------------*/
function newUser($firstName,$lastName,$emailUser,$active,$conn){
//a function to insert a user into a database is here
}
//newUser function enters names in database
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors------------------------------*/
function errorCheck($formNames, $nameSplit, $fullname){
$isValid = false;
if (empty($fullname)) {
$_SESSION['error'][] = '<br><br> Error: Name Missing Here: '.$fullname.'<br><br>';
} elseif (empty($nameSplit[0])) {
$_SESSION['error'][] = '<br><br> Error: First Name Missing Here: '.$fullname.'<br><br>';
} elseif (empty($nameSplit[1])) {
$_SESSION['error'][] = '<br><br> Error: Last Name Missing Here: '.$fullname.'<br><br>';
} elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
$_SESSION['error'][] = '<br><br> Error: Illegal Character Found in: '.$fullname.'<br><br>';
} else {
$isValid = true;
}
return $isValid;
}
//errorCheck function tests for errors in names and stops them from being entered in the
//database if there are errors in the name. Allows good names to go through
/*-----------------------------End Function for Errors---------------------*/
/*--------------------------Function for Redirect--------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
//redirect function uses a javascript script to redirect user because headers have already been sent.
/*-----------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here//
// Initialize empty error array
$_SESSION['error'] = array();
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//I open the database here
//opens the database
if (errorCheck($formNames, $nameSplit, $fullname)) {
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);//do this BELOW only for names that have no errors
}//ends if of errorCheck
}//ends fullnames foreach
if (count($_SESSION['error']) == 0) {
redirect('viewAll.php');
} else {
redirect('form.php');
}
/*Redirects to viewAll page only once and as long as no errors have been found*/
Your
class User {
public $nameStore, $fName, $lName, $email;
public function __construct ($fName, $lName, $email) {
$this->$fN = $fName;
$this->$lN = $lName;
$this->$eN = $email;
}
I would break this up into more specific parts such as GET and SET for each value you are trying to store in the Class:
class User {
private $fName, $lName, $email;
public function set_firstname($fname){
$this->fName = $fname;
}
public function set_surname($lName){
$this->lName = $lName;
}
public function set_email($email){
$this->email = $email;
}
public function get_email(){
return $this->email;
}
public function get_fname(){
return $this->fName;
}
public function get_surname(){
return $this->lName;
}
Then when you create the class, you can add and return each value individually, rather than forcing yourself to do them all at once. This is more flexible. But you can also add the values at the creation of the class as well if you wish, using the __construct similar to what you had already:
public function __construct ($fName = null, $lName = null, $email = null) {
if(!empty($fName)){
$this->set_firstname($fName);
}
if(!empty($lName)){
$this->set_surname($lName);
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) !== false){
$this->set_email($email);
}
}
What this does is for each non-empty value it runs the corresponding SET method. Also checking that the email value is valid before saving it. If no values are passed to the class then it doesn't save anything.
Your setting up of the class is incorrect, firstly you need to include the class file into the working PHP so at the top of your page add:
include "path/to/users.class.php";
And then initiate the class correctly:
$userClassInstance = new User($firstName,$lastName,$emailUser);
When the above line runs, you will then have a User object containing three variables referenced as $userClassInstance. you can do var_dump($userClassInstance);
Be careful as your code has newUser as one line and also has an incorrect number of variables in the construct statement. Generally all the functions in a page should be placed inside an appropriate class, so all your string management functions such as errorCheck() could be put into the Users class to check the values given before assigning them to the variables in the class.
Finally, to view the stored variables you would then do:
print $userClassInstance->get_fname(); //will outout the value of the class $fName

Method Chaining PHP

I have a quick question that's killing my head.
I'm trying to make a Form Validation System with Method Chaining in PHP
What I want to do is to be able to call for example (please check the code comments):
$firstname = $OBJECT->Forms->Field("First Name", "firstname"); //This one doesn't validate, but just puts what's on firstname field on to $firstname. But this way doesn't work for me, because I have to return the object so it can be chainable and not the variable of the POST. How can I do this?
$firstname = $OBJECT->Forms->Field("First Name", "firstname")->Validate(); //this one validates if the field is not empty and if it's empty it'll insert the first parameter ("First Name") onto an array to display the errors.
$email = $OBJECT->Forms->Field("Email", "email")->Validate()->Email(); //This one does the same as above but validates Email and inserts the value of the email field onto $email
but I prefer the next one...
$email = $OBJECT->Forms->Field("Email", "email")->Validate->Email(); //I'd rather prefer this method but I don't know how to do it without using the parenthesis on the Validate method.
I can only make it work like this
$firstname = $OBJECT->Forms->Field("First Name", "firstname")->Validate();
and
$firstname = $OBJECT->Forms->Field("First Name", "firstname")->Validate()->Email();
Without ->Validate(); I can't seem to make it work (Like this: $firstname = $OBJECT->Forms->Field("First Name", "firstname");)
The code is kinda mess to share. But the code is simple... I have a forms.class.php and a validate.class.php.
The forms.class.php creates an instance of Validate class from validate.class.php and the Forms Object is passed through the Validate class on the constructor.
I want to be able to do:
$OBJECT->Forms->Field();
$OBJECT->Forms->Field()->Validate();
$OBJECT->Forms->Field()->Validate()->Email;
$OBJECT->Forms->Field()->Validate()->Telephone;
or this preferebly:
$OBJECT->Forms->Field();
$OBJECT->Forms->Field()->Validate;
$OBJECT->Forms->Field()->Validate->Email;
$OBJECT->Forms->Field()->Validate->Telephone;
Only figured out:
$OBJECT->Forms->Field()->Validate();
$OBJECT->Forms->Field()->Validate()->Email();
$OBJECT->Forms->Field()->Validate()->Telephone();
But any form is OK
Thank you.
See if this is what you are trying to do:
<?php
class FormValidate
{
protected $args;
public $valid;
public function Forms()
{
// Don't know what this function is supposed to do....
return $this;
}
public function Validate()
{
$numargs = func_num_args();
$this->args = array();
if($numargs == 2) {
$vals = func_get_args();
$this->args[$vals[1]] = $vals[0];
$this->valid = true;
}
else
$this->valid = false;
if(isset($this->args['firstname']) && !empty($this->args['firstname']))
return true;
return $this;
}
public function Email()
{
if(isset($this->args['email'])) {
if(filter_var($this->args['email'],FILTER_VALIDATE_EMAIL))
return $this->valid = $this->args['email'];
}
return $this->valid = false;
}
public function Telephone()
{
if(isset($this->args['telephone'])) {
if(preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/',$this->args['telephone']))
return $this->valid = $this->args['telephone'];
}
return $this->valid = false;
}
}
$test = new FormValidate();
// These will throw a fatal error on the base Validate('First Name','firstname')
// if you add another method to the chain like so: ->Validate('First Name','firstname')->Email();
echo $test->Forms()->Validate('123-876-0987','telephone')->Telephone();
?>

How can I assign a variable to a query in codeigniter

For my project I need to check if some variables are empty and if they are then:
The user gets a custom view with a message on which variable is missing.
The developer/me must be able to see the query which was sent to check if there are no failure's in the query.
My question is how can I assign a variable (for example $checkQuery) to my query so that it has all the values and I can check it within the error log.
Query
function createUser($data){
$this->firstname = $data['firstname'];
$this->lastname = $data['surname1'].' '.$data['surname2'];
$this->address = $data['adres'];
$this->zipcode = $data['zipcode'];
$this->mail = $data['mail'];
$this->phonenumber = $data['phonenumber'];
$this->db->insert('User',$this);
//Check if the change was succesfull
return ($this->db->affected_rows() != 1) ? false : true;
}
Function for errorLog
function errorLog($var){ //Get the variable that you have passed from your helper
$mail = "Email was empty";
$firstname ="Firstname was empty";
if($var == 'mail') //Change the error function based on what has been passed
{
return log_message('error', $mail); //Here use the return type
}
if($var == 'firstname')
{
return log_message('error', $firstname); //Here use the return type
}
}
The view for the user is done which I've done with just a simple array but the only thing I see at the moment is just if firstname or email is was empty.
So is it possible to use a PHP variable in which I can assign the submitted values and can put these into my error log preferably using log_message

PHP Check Function

I have a check function:
function checkCandidateEmail($email)
{
$email = $_POST;
if($email)
{
$candemail = (SQL);
if(isset($candemail['email']))
{
return TRUE;
} else {
return FALSE;
}
return $canEmailCheck;
}
}
I have started to create a function but I am getting NULL
function checkCandidateEmail($email)
{
$email = $_POST; // being immediately overwritten - redundant argument.
if($email) // Since $email isn't an optional argument, you'll get a PHP warning if it is missing, making this check confusing.
{
$candemail = (SQL); // Evaluating a constant? this will be bool
if(isset($candemail['email'])) // Since $candemail is a bool and not an array, this will never return true
{
return TRUE;
} else {
return FALSE;
} // this entire if/else block can be simplified to this: return (isset($candemail['email']));
return $canEmailCheck; // this is an undefined variable and will never get returned anyway because of the above return statements.
}
}
Please, elaborate more on your questions next time. I am not sure what you attempt to compare, if the $_POST with the SQL query or the argument passed with the SQL query. I assume the former.
If the email from that SQL table row equals the submitted email, returns TRUE. Else, returns FALSE. Really simplified version. Now it also checks if the user provided an email:
function checkCandidateEmail()
{
if (!$_POST['email']) echo "Error, please provide an email";
else
{
$candemail = (SQL); // Return a row from a query
return $candemail['email'] == $_POST['email'];
}
}
If an argument is passed, compares that against the database. If none is passed, compares the submitted $_POST['email'] against the database.
function checkCandidateEmail($email=null)
{
$candemail = (SQL); // Return a row from a query
if (!$email) $email = $_POST['email'];
return $candemail['email'] == $email;
}
NOTE: In both cases you have to substitute SQL for the right string and function depending on your database.
NOTE 2: Make sure that your query returns an email, as this simple code does not check if both strings are empty.

More professional error handling

I have a contact form and I handle errors by checking each field one-by-one with an "if" statement. I find this hard and I can't seem to find a better/more productive way to get them working. I would also like a heading saying "Error" if one (or more) is true. But I cant get them to work with the separate "if" statements.
Here is my code:
$name = $_POST['name']; //get data from the form
$email = $_POST['email'];//get data from the form
$message = $_POST['message'];//get data from the form
if($name == ""){
echo"<p class='error'>Please enter a name.</p>";
}
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$email)){
echo "<p class='error'>Your email address is not valid.</p>";
}
if($message == ""){
echo"<p class='error'>Please enter a message.</p>";
}
else{
echo"all ok, send email code...";
}
Edit: These errors are for the validation of the form.
But I cant get them to work with the separate "if" statements.
Just store error in a variable
$error = array();
if($name == ""){
$error[] = "Please enter a name.";
}
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$email)){
$error[] = "Your email address is not valid.";
}
if($message == ""){
$error[] = "Please enter a message.";
}
if (!$error) {
// do not echo anything here
// but send an email
// and use header("Location:") to redirect a user to thanks page
} else {
echo "Error";
foreach ($error as $line) {
echo "<p class='error'>$line</p>";
}
}
You are looking for validator class. Also see:
Building An Extensible Form Validator Class
The most professional way would be to have each field be an object with a validation method.
Then you can call each field object and ask them to validate themself.
If you would like to go any further (might be overkill though) you put your objects in a list.
Each of these objects are child to an interface with the validation method. So for each object in the list, you call the validation method.
Well, you can't check all fields together as different rules may apply to each one. So what you are doing is fine, except for a mistake you made: The else part should only be echoed, when no error occurred, but in your situation the else only applies to the last if. So even if the validation of name and email fails, as long as the message one does not, the final action is done.
You could easily add some $has_error variable that contains true as soon as an error was found. Or you could use an array that holds all error messages like this:
$errors = array();
if ( empty( $name ) )
$errors[] = 'Please enter a name.';
if ( !eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email ) )
$errors[] ='Your email address is not valid.';
if ( empty( $message ) )
$errors[] = 'Please enter a message.';
// individual checks done
if ( sizeof( $errors ) > 0 )
{
echo '<p class="error"><strong>Errors found:</strong><br />';
echo implode( '<br />', $errors );
echo '</p>';
}
else
{
echo 'No error, everything is fine.';
}
First, don't use ereg*() functions for regular expressions matching, these are deprecated and slow. Use the preg_*() functions instead.
Also take a look at PHP's filter extension.
It provides functions to check and validate various data which you can use directly or incorporate into your own validator functions.
EDIT: Example for checking an e-mail address (see also examples on php.net):
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
echo 'Invalid e-mail "'.$email.'"';
Speaking of validation in an object-oriented manner, you could have a generic validator class with basic validation functions (where you could also integrate filter functions for a consistent API).
Additionally, if your data logically belongs together such that you can group them into objects and manage them as such, implement a validate() method in the classes of these objects that checks the object's properties by utilizing the filter functions and/or your validator class.
class Message {
private $name;
private $email;
private $text;
...
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getEMail() {
return $this->email;
}
public function setEMail($email) {
$this->email = $email;
}
...
public function validate() {
$errors = array();
$nameLength = strlen($this->name);
if ( ($nameLength === 0) or ($nameLength > self::NAME_MAX_LENGTH) )
$errors['name'] = 'Name must be between 1 and '.self::NAME_MAX_LENGTH.' characters.';
if ( !Validator::isEMail($this->email) )
$errors['email'] = 'Invalid e-mail "'.$this->email.'"';
// Other checks
...
// Return TRUE if successful, otherwise array of errors
return ( count($errors) === 0 ? true : $errors );
}
}
Then, you could load all your form inputs into your object like this:
$message = new Message();
$message->setName($_POST['name']);
$message->setEMail($_POST['email']);
$message->setText($_POST['text']);
...
$result = $message->validate();
if ( $result === true ) {
// Success
} else {
// Error
foreach ($result as $validationError) {
// Print error
echo htmlentities($validationError).'<br />';
}
}

Categories