Not displaying values from an array - php

I have a form that has this code in it, so I can echo the errors as I check the fields from a class:
<?php if( isset($_POST['send'])){
$new_user = new Register();
$new_user->check_required_fields($_POST);
$new_user->display_errors();
}
?>
and the class is:
<?php
class Register extends Database
{
public $fname;
public $lname;
public $uname;
public $email;
public $pass1;
public $pass2;
public $year;
public $month;
public $day;
public $required_array;
public $error;
public $errors = array();
public function check_required_fields($required_array)
{
if(in_array('', $required_array)) {
$errors[] = "One or more fields are missing";
//var_dump($errors);
}
else
{
$errors[] = "All fields are ok";
$this->fname = $required_array['fname'];
$this->lname = $required_array['lname'];
$this->uname = $required_array['lname'];
$this->email = $required_array['email'];
$this->pass1 = $required_array['pass1'];
$this->pass2 = $required_array['pass2'];
$this->year = $required_array['year'];
$this->month = $required_array['month'];
$this->day = $required_array['day'];
}
}
public function display_errors ($errors)
{
foreach ($errors as $error){
echo $error;
}
}
For some reason it will not display the $errors array and I am not sure why? I would be greatful for any help, thanks.

Try using
$this->errors
in both check_required_fields and display_errors.

public function display_errors ($errors)
{
foreach($errors as $error){
echo $error;
}
}
the "$errors" you use in the foreach statement is the one in the function display_errors's parameter list, and when you invoke the function, you didn't give any parameter, so this variable would be empty
you should use $this->errors in the foreach statement

Related

Setting the value of properties in PHP

I have a class called members, i have an example below. What i am asking is how do i set the values of title. So for example , i only allow Mr, Mrs, Miss and any other values will throw out an error stating Only Mr,Mrs,Miss is allowed , Firstname must be John..
class Member
{
private $title;
private $firstname;
public function __construct( $title )
{
$this->title = $title;
}
public function showProfile()
{
echo "<dl>";
echo "<dt>Title:</dt><dd>$this->title</dd>";
echo "</dl>";
}
}
$data = new Member( "Mrr" );
$data->showProfile();
You can try this , hope this will be helpful.
Try this code snippet here
<?php
ini_set("display_errors", 1);
class Member
{
private $title;
public function __construct($title)
{
if(!in_array($title, ["Mr","Mrs","Miss"]))
{
throw new Exception("Only Mr,Mrs,Miss are allowed!");
//or you can simple echo out your message instead of exception
}
$this->title = $title;
}
public function showProfile()
{
echo "<dl>";
echo "<dt>Title:</dt><dd>$this->title</dd>";
echo "</dl>";
}
}
$data = new Member("Mrr");
Optionally you can set a variable for this error with in the class, which prevent further execution of methods of class script. You can also do it like this
Solution 2:
Try this code snippet here
<?php
ini_set("display_errors", 1);
class Member
{
private $title;
private $error=false;
public function __construct($title)
{
if(!in_array($title, ["Mr","Mrs","Miss"]))
{
$this->error=true;
}
$this->title = $title;
}
public function showProfile()
{
if($this->error!==true)
{
echo "<dl>";
echo "<dt>Title:</dt><dd>$this->title</dd>";
echo "</dl>";
}
else
{
echo "Only Mr,Mrs,Miss is allowed!";
}
}
}
$data = new Member("Mrr");
$data->showProfile();
Make a setter
function setTitle($newTitle){
if(in_array($newTitle, array('Mr', 'Miss', 'Mrs' ))
$this->title=$newTitle;
else
echo 'ERROR';
}
And then call it from the constructor
I didnt like any of the answers.
Here's mine. I think you should use a mutator in your solution. The member class should be decoupled from the setter.
class Member
{
private $title;
public function setTitle($title)
{
$this->title = $title;
}
public function showProfile()
{
return sprintf("<dl><dt>Title</dt><dt><dd>%s</dd></dt></dl>" , $this->title );
}
}
class TitleProperty
{
protected $name = 'title';
protected $allowed_allowed = ['mr', 'mrs', 'miss'];
public $errors = [];
/**
*#param Member $member
*#param string $value
*/
public function __construct( Member $member, $value )
{
if(!in_array($value, $this->allowed_allowed )){
$this->errors[] = "Only Mr,Mrs,Miss is allowed";
}
else{
$member->setTitle( $value );
}
}
}
$member = new Member();
$property = new TitleProperty($member, 'hello');
if($property->errors){
print_r($property->errors);
}
else{
echo 'title set.';
}
There you go

PHP error printing inside class

I'm trying to play with a class and not understand how it works. Some people explained how to pass variables between a function. My problem at the moment is errors. And how to extract errors from the class and print to the screen. My output is username only. How to get errors?
class form
{
protected $username;
protected $password;
protected $errors = array();
function __construct($username, $password){
$this->username = $username;
$this->password = $password;
}
public function get_errors()
{
return $this->errors;
}
public function getPassword(){
return $this->password;
}
public function getUserName() {
return $this->username;
return $this->errors = "No MySQL connection.";
}
}
$test = new form('name1', 'passw2');
echo $test->getUserName();
You can not return two time inside a function. But you can achieve what you want like below:-
public function getUserName() {
$this->errors = "No MySQL connection.";
return $this->username.'<br/>'.$this->errors;
}
Note:- this is the solution but your code have no mean. You have to do some useful stuff
try throw exception
public function getUserName() {
if($this->errors) {
throw new Exception($this->errors);
}
return $this->username;
}
$test = new form('name1', 'passw2');
try {
echo $test->getUserName();
} catch(Exception $error) {
echo 'Error:'.$error->getMessage();
}
If you get error you can simple catching this error and output to web,console or error log;
class form
{
protected $username;
protected $password;
protected $errors = array();
function __construct($username, $password){
$this->username = $username;
$this->password = $password;
}
public function getErrors()
{
return $this->errors;
}
public function getPassword()
{
return $this->password;
}
public function getUserName()
{
/* Add some an error to an error's array */
$this->errors[] = "No MySQL connection.";
return $this->username;
}
}
$test = new form('name1', 'passw2');
echo $test->getUserName();
var_dump($test->getErrors()); /* Get errors from a class */

Error handling in PHP class

I still playing with PHP and OOP. But not understand how to pull back errors from the class.
index file
include 'class.php';
$test = new magic('', '', '33');
$test->getfullname();
foreach ($test->get_errors() as $error) {
echo $error . '<br>';
}
class:
class magic
{
private $name;
private $surname;
private $age;
private $errors = array();
function __construct($name, $surname, $age)
{
$this->name = $name;
$this->surname = $surname;
$this->age = $age;
}
public function get_errors()
{
return $this->errors;
}
public function getname()
{
if (!empty($this->name)) {
return true;
} else {
array_push($this->errors, 'Please check name');
return false;
}
}
public function getsurname()
{
if (!empty($this->surname)) {
return true;
} else {
array_push($this->errors, 'Please check surname');
return false;
}
}
public function getfullname()
{
if (($this->getname()) && ($this->getsurname())) {
echo $this->name . ' ' . $this->surname;
}
}
}
My question is why when name or surname is empty then returning please check name or surname but when both are empty then return only first? How to candle these type errors in PHP class and what is best practice to do that?
I don't think i can use try/catch exceptions in this scenario.
I suggest handling errors in the constructor and throwing exception.
class magic
{
/**
* #param string $name
* #param string $surname
* #param int $age
* #throws Exception
*/
public function __construct($name, $surname, $age)
{
$errors = [];
if (empty($name)) {
$errors[] = 'Name is required.';
}
if (empty($surname)) {
$errors[] = 'Surname is required.';
}
if (!empty($errors)) {
throw new Exception(implode('<br />', $errors));
}
$this->name = $name;
$this->surname = $surname;
$this->age = $age;
}
public function printFullname()
{
echo $this->name . ' ' . $this->surname;
}
}
client:
include 'class.php';
try {
$test = new magic('', '', '33');
$test->printFullname();
} catch (Exception $exc) {
echo $exc->getMessage(); //error messages
}
There's no reason you can't use exceptions in this scenario, it's what they are designed for, much more elegant than this kind of $this->geterrors(); stuff.
http://php.net/manual/en/language.exceptions.php

PHP - What is wrong? Learning MVC - Beginner

Hy,
i started learning PHP and i created a simple MVC Style Codebase.
The Script just generates a random number and displays this numer. I also write a function to display the number shown before but it does not work. The value is empty. Can you help me out, i have no clue whats wrong and there is no php error thrown.
view.php
<?php
class View
{
private $model;
private $view;
public function __construct()
{
$this->model = new Model();
}
public function output()
{
echo 'Current Entry: ';
echo $this->model->getData();
echo '<br />';
echo 'Update';
echo '<br />';
echo 'Last';
}
public function getModel()
{
return $this->model;
}
}
controller.php
<?php
class Controller
{
private $model;
private $view;
public function __construct($view)
{
$this->view = $view;
$this->model = $this->view->getModel();
}
public function get($request)
{
if (isset($request['action']))
{
if ($request['action'] === 'update')
{
for ($i = 0; $i<6; $i++)
{
$a .= mt_rand(0,9);
}
$this->model->setData($a);
}
elseif ($request['action'] === 'preview')
{
$this->model->setLast();
}
else
{
$this->model->setData('Wrong Action');
}
}
else
{
$this->model->setData('Bad Request');
}
}
}
model.php
<?php
class Model
{
private $data;
private $last;
public function __construct()
{
$this->data = 'Default';
}
public function setData($set)
{
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$this->last = $this->data;
}
$this->data = $set;
}
public function getData()
{
return $this->data;
}
public function setLast()
{
$this->data = $this->last;
}
public function getLast()
{
return $this->last;
}
}
index.php
<?php
require_once 'controller.php';
require_once 'view.php';
require_once 'model.php';
$view = new View();
$controller = new Controller($view);
if (isset($_GET) && !empty($_GET)) {
$controller->get($_GET);
}
$view->output();
Are there any other, bad mistakes in the Script?
Any input very welcome! :)
The problem with your code is that PHP does not preserve variable values between requests, therefore, when you set your $model->last value here:
$this->last = $this->data;
It gets reset on your next request.
You may want to store $last value in a session or a cookie instead. Something like:
$_SESSION['last'] = $this->data;
And then when you are instantiating your model you could initialize it with a value stored in a session if available:
index.php - add session_start() at the beginning
model.php:
public function __construct()
{
$this->data = isset($_SESSION['last']) ? $_SESSION['last'] : 'Default';
}
public function setData($set)
{
$this->data = $set;
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$_SESSION['last'] = $this->data;
}
}
controller.php
elseif ($request['action'] === 'preview')
{
//Remove this
//$this->model->setLast();
}

php : Warning: Invalid argument supplied for foreach()

I just can't figure it out.. but i got a feeling the problem is around there when im throwing the exception messages. I got almost the same code in my registration class. There is just give the errors array the messages normaly like $this->errors[] = "some error".
<?php
class class_login
{
private $id;
private $username;
private $password;
private $passmd5;
private $errors;
private $access;
private $login;
private $ltoken;
public function __cunstruct()
{
$this->errors = array();
$this->login = isset($_POST['login'])? 1:0;
$this->access = 0;
$this->ltoken = $_POST['ltoken'];
$this->id = 0;
$this->username = ($this->login)? $this->filter($_POST['lusername']) : $_SESSION['username'];
$this->password = ($this->login)? $this->filter($_POST['lpassword']) : '';
$this->passmd5 = ($this->login)? md5($this->password) : $_SESSION['password'];
}
public function isLoggedIn()
{
($this->login)? $this->verifyPost() : $this->verifySession();
return $this->access;
}
public function filter($var)
{
return preg_replace('/[^a-zA-Z0-9]/','',$var);
}
public function verifyPost()
{
try
{
if(!$this->tokenValid())
throw new Exception('Invalid Form Submission!');
if(!$this->isDataValid())
throw new Exception('Ivalid Form Data!');
if(!$this->verifyDatabase())
throw new Exception('Invalid Username/Password!');
$this->access = 1;
$this->registerSession();
}
catch(Exception $e)
{
$this->errors[] = $e->getMessage();
}
}
public function verifySession()
{
if($this->sessionExist() && $this->verifyDatabase())
$this->access = 1;
}
public function verifyDatabase()
{
include('db_connect.php');
$data = mysql_query("SELECT ID FROM users WHERE username = '($this->username)' AND password = '($this->passmd5)'");
if (mysql_num_rows($data))
{
list($this->id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
return false;
}
public function isDataValid()
{
return (preg_match('/[^a-zA-Z0-9](5,12)$/', $this->username) && preg_match('/[^a-zA-Z0-9](5,12)$/', $this->password))? 1:0;
}
public function tokenValid()
{
return (!isset($_SESSION['ltoken']) || $this->ltoken != $_SESSION['ltoken'])? 0 : 1;
}
public function registerSession()
{
$_SESSION['ID'] = $this->id;
$_SESSION['username'] = $this->username;
$_SESSION['password'] = $this->passmd5;
}
public function sessionExist()
{
return (isset($_SESSION['username']) && isset($_SESSION['password']))? 1 : 0;
}
public function show_errors()
{
foreach($this->errors as $key=>$value)
echo $value."</br>";
}
}
?>
The constructor is called __construct, not __cunstruct.
I see you are setting $this->errors to an array in your __cunstruct function, but since it is not __construct it may never be set.
You need a associative array for
foreach($this->errors as $key=>$value)
But you have no one. ($this->errors[] = $e->getMessage();)
With out an associative array you must use:
foreach($this->errors as $value)
public function __cunstruct() <------ The error is probably here. It is __construct
{
$this->errors = array();
$this->login = isset($_POST['login'])? 1:0;
$this->access = 0;
$this->ltoken = $_POST['ltoken'];
$this->id = 0;
$this->username = ($this->login)? $this->filter($_POST['lusername']) : $_SESSION['username'];
$this->password = ($this->login)? $this->filter($_POST['lpassword']) : '';
$this->passmd5 = ($this->login)? md5($this->password) : $_SESSION['password'];
}
You have a typo.... _construct and not _construct

Categories