help with array - php

What am i doing wrong here? The username string is less than 2 chars but it still dont set error[]?
Register:
$errors = array();
$username = "l";
validate_username($username);
if (empty($errors)) {
echo "nothing wrong here, inserting...";
}
if (!empty($errors)) {
foreach ($errors as $cur_error)
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
function validate_username($username) {
$errors = array();
if (strlen($username) < 2)
$errors[] = "Username too short";
else if (strlen($username) > 25)
$errors[] = "Username too long";
return $errors;
}

It's because you are not assigning the return value of validate_username() to any variable.
Try
$errors = validate_username($username);

Change validate_username($username); to $errors = validate_username($username);
Your function is affecting a local variable named errors, not the global errors that you may have been expecting.
Further, your code can be cleaned up a little bit as follows
$username = "l";
$errors = validate_username($username);
// No errors
if ( empty($errors) ) {
echo "nothing wrong here, inserting...";
}
// Errors are present
else {
foreach ( $errors as $cur_error ) {
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
}
function validate_username($username) {
$errors = array();
$len = strlen($username);
if ( $len < 2 ) {
$errors[] = "Username too short";
} elseif ( $len > 25 ) {
$errors[] = "Username too long";
}
return $errors;
}

you're not returning it the right way, you need:
$errors = validate_username($username)

you forgot to assign $errors
$errors = validate_username($username);

**//TRY THIS INSTEAD**
$errors = array();
$username = "l";
**$errors = validate_username($username);**
if (empty($errors)) {
echo "nothing wrong here, inserting...";
}
if (!empty($errors)) {
foreach ($errors as $cur_error)
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
function validate_username($username) {
$errors = array();
if (strlen($username) < 2)
$errors[] = "Username too short";
else if (strlen($username) > 25)
$errors[] = "Username too long";
return $errors;
}

Related

How can I define a variable inside a function?

how I can define a variable inside a PHP function and make it reachable from another function? I want to set $error variable to "1".
This how would the code look like:
function checkthename ($name){
if ($name == "TESTTEST"){
echo $error = 0;
}
else {
echo $error = 1;
}
}
function phone ($phone){
if ($name == "TESTTEST"){
echo $error = 0;
}
else {
echo $error = 1;
}
}
etc.
And in end of the code there would be an another function which is checking if there is any $error variable set to 1
function checktheerror($error){
if ($error == 0){
echo "no error in this code";
}
elseif ($error == 1){
echo "there is one or multiple errors";
}
}
Thank you so much for your help!

I need help in form validations of php its complex

I am having problem in form validations the error im getting is something like this
Fatal error: Uncaught Error: Unsupported operand types in C:\xampp\htdocs\LSR\signup.php:22 Stack trace: #0 {main} thrown in C:\xampp\htdocs\LSR\signup.php on line 22
function check_empty_fields($required_fields_array){
$form_errors = array();
foreach($required_fields_array as $name_of_field){
if (!isset($_POST[$name_of_field]) || $_POST[$name_of_field] == NULL) {
$form_errors[] = $name_of_field . "Is a REQUIRED FIELD";
}
}
return $form_errors;
}
function check_min_length($fields_to_check_length){
$form_errors = array();
foreach($fields_to_check_length as $name_of_field => $minimum_length_required){
if(strlen(trim($_POST[$name_of_field])) < $minimum_length_required){
$form_errors[] = $name_of_field . "Is too short must be {$minimum_length_required} characters long";
}
}
return $form_errors;
}
function check_email($data){
$form_errors = array();
$key = "email";
if(array_key_exists($key, $data)){
if($_POST[$key] != null){
$key = filter_var($key, FILTER_SANITIZE_EMAIL);
if (filter_var($_POST[$key], FILTER_VALIDATE_EMAIL) === false) {
$form_errors[] = $key . "is not a valid email address";
}
}
}
return $form_errors;
}
function show_errors($form_errors_array){
$errors .= "<p><ul style='color: red;'>";
foreach($form_errors_array as $the_error){
$errors .="<li>{$the_error}</li>";
}
$errors .= "</ul></p>";
return $errors;
}
Try on http://sandbox.onlinephpfunctions.com/code/c36fd6eb9b3a8e555364d99dd90cd9281100c884
<?php
function check_empty_fields($required_fields_array)
{
if (!is_array($required_fields_array)) {
return array();
}
$form_errors = array();
foreach ($required_fields_array as $name_of_field) {
if (empty($_POST[$name_of_field])) {
$form_errors[] = "'$name_of_field' is a REQUIRED FIELD";
}
}
return $form_errors;
}
function check_min_length($fields_to_check_length)
{
if (!is_array($fields_to_check_length)) {
return array();
}
$form_errors = array();
foreach ($fields_to_check_length as $name_of_field => $minimum_length_required) {
if (isset($_POST[$name_of_field]) && strlen(trim($_POST[$name_of_field])) < $minimum_length_required) {
$form_errors[] ="'{$name_of_field}' is too short must be '{$minimum_length_required}' characters long";
}
}
return $form_errors;
}
function check_email($fields_to_check_email = array('email'))
{
if (!is_array($fields_to_check_email)) {
return array();
}
$form_errors = array();
foreach ($fields_to_check_email as $name_of_field) {
if (isset($_POST[$name_of_field]) && !filter_var($_POST[$name_of_field], FILTER_VALIDATE_EMAIL)) {
$form_errors[] = "'{$name_of_field}' is not a valid email address";
}
}
return $form_errors;
}
function show_errors($form_errors_array)
{
$errors = '';
$errors .= "<p><ul style='color: red;'>";
foreach ($form_errors_array as $the_error) {
$errors .= "<li>{$the_error}</li>";
}
$errors .= "</ul></p>";
return $errors;
}
// Tests...
$_POST = array(
'name' => 'Test',
'null_name' => null,
'empty_name' => '',
'email' => 'test#mail.com',
'invalid_email' => 'test##mail.com',
);
$empty_errors = array();
$empty_errors = check_empty_fields(array('name', 'null_name', 'empty_name', 'undefined_name'));
echo 'Empty errors:', show_errors($empty_errors), "\n";
$min_length_errors = array();
$min_length_errors = check_min_length(array('name' => 4, 'empty_name' => 4));
echo 'Min length errors:', show_errors($min_length_errors), "\n";
$email_errors = array();
$email_errors = check_email(array('email', 'invalid_email'));
echo 'Email errors:', show_errors($email_errors), "\n";

Add input's errors in array with for

I have one problem in PHP code. It did not give me whatever output. Where my mistake?
if (isset($_POST['regBtn'])) {
$fname = strip_tags(trim($_POST['fname']));
$lname = strip_tags(trim($_POST['lname']));
$email = strip_tags(trim($_POST['email']));
$password = strip_tags(trim($_POST['password']));
$errMsg = array();
for($i=0; $i<=3;$i++) {
if (strlen($fname) < 0) {
$errMsg[$i] = "Գրեք Ձեր անունը ամբողջությամբ։";
} elseif (strlen ($lname) <0) {
$errMsg[$i] = "Գրեք Ձեր ազգանունը ամբողջությամբ";
} elseif (strlen($email) < 0) {
$errMsg[$i] = "Գրեք Ձեր էլ․ հասցեն";
} elseif (strlen($password) < 6) {
$errMsg = "Գաղտնաբառը պետք է պարունակի առնվազն 6 նիշ";
} }
var_dump ($errMsg);
}
else {
}
Several problems here, assuming that you have a form input with name="regBtn" which is required for this code to run:
strlen will not be < 0 though it may be 0. Use empty or a number greater than 0 if needed.
elseif will only execute if the if fails so just use if.
No need to loop, just use multiple if blocks and dynamically append to the error array [].
if (isset($_POST['regBtn'])) {
$fname = strip_tags(trim($_POST['fname']));
$lname = strip_tags(trim($_POST['lname']));
$email = strip_tags(trim($_POST['email']));
$password = strip_tags(trim($_POST['password']));
$errMsg = array();
if (empty($fname)) { // or use strlen < 2 or < 3 or whatever like $password
$errMsg[] = "Գրեք Ձեր անունը ամբողջությամբ։";
}
if (empty($lname)) {
$errMsg[] = "Գրեք Ձեր ազգանունը ամբողջությամբ";
}
if (empty($email)) {
$errMsg[] = "Գրեք Ձեր էլ․ հասցեն";
}
if (strlen($password) < 6) {
$errMsg[] = "Գաղտնաբառը պետք է պարունակի առնվազն 6 նիշ";
}
var_dump ($errMsg);
}
Also, you probably want to trim after strip_tags in case it leaves space(s):
$fname = trim(strip_tags($_POST['fname']));

PDO insert trying to bind wrong number of params

I am having trouble figuring out where my insert (using pdo) is failing. I passed it 19 parameters via an array, and then bound 19 values from that same array.
It fails at the bind step with the following error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens'
I was wondering if you guys would be able to figure out why its failing. The code I am using is below:
addevent.php
if(isset($_POST['add_event'])){
$eventDetails = $_POST;
$event_code = htmlspecialchars($eventDetails['ecode']);
$event_title = htmlspecialchars($eventDetails['etitle']);
$location = htmlspecialchars($eventDetails['location']);
$start_date = htmlspecialchars($eventDetails['start_date']);
$end_date = htmlspecialchars($eventDetails['end_date']);
$super_early_date = htmlspecialchars($eventDetails['super_early_date']);
$early_date = htmlspecialchars($eventDetails['early_date']);
$tax_type = htmlspecialchars($eventDetails['tax_desc']);
$tax_rate = htmlspecialchars($eventDetails['tax_rate']);
$is_call_open = htmlspecialchars($eventDetails['is_call_open']);
$domain_name = htmlspecialchars($eventDetails['domain']);
$sold_out_msg = htmlspecialchars($eventDetails['sold_out_msg']);
$group_min = htmlspecialchars($eventDetails['group_discount_min']);
$group_num = htmlspecialchars($eventDetails['group_discount_per']);
//errors array that will be passed to view if there are errors;
$errors = array();
//if there are contents in the error array from previous execution empty error
if(!empty($errors)){ unset($errors); }
//if any of these fields are empty add them to the array
if(empty($event_code)) { array_push($errors, ucwords('event code is required')); }
if(empty($event_title)) { array_push($errors, ucwords('event title is required')); }
if(empty($location)) { array_push($errors, ucwords('location is required')); }
if(empty($start_date)) { array_push($errors, ucwords('start date is required')); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/',$start_date) == 0) { array_push($errors, ucwords('incorrect format for start date, it should be').' yyyy-mm-dd'); }
if(empty($end_date)) { array_push($errors, ucwords('end date is required')); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $end_date) == 0) { array_push($errors, ucwords('incorrect format for end date, it should be').' yyyy-mm-dd'); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $super_early_date) == 0) { array_push($errors, ucwords('incorrect format for super early bird date, it should be').' yyyy-mm-dd'); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $early_date) == 0) { array_push($errors, ucwords('incorrect format for early bird date, it should be').' yyyy-mm-dd'); }
if($tax_type == 'none') { array_push($errors, ucwords('tax type is required')); }
if(empty($tax_rate)) { array_push($errors, ucwords('tax rate is required')); }
if(empty($domain_name)) { array_push($errors, ucwords('domain name is required')); }
if(preg_match('/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/', $domain_name) == 0) { array_push($errors, ucwords('domain name is not valid')); }
if(empty($sold_out_msg)) { array_push($errors, ucwords('sold out message is required')); }
if(!empty($group_min) && empty($group_num)) { array_push($errors, ucwords('group discount (percent) is required')); }
if(!empty($errors)){
$this->set('errors', $errors);
}
else{
//remove the add_event button from the event
$add_event_index = array_pop($eventDetails);
$keys = array_keys($eventDetails);
$addEvent = "INSERT INTO v_events (" . implode(",", $keys) . ") VALUES (";
for($i = 0; $i < sizeof($eventDetails); $i+=1){
if($i == 0) { $addEvent .= "?"; }
else { $addEvent .= ",?"; }
}
$addEvent .= ")";
$success = $this->Cms->query($addEvent, $eventDetails);
if(!$success){
print_r($this->Cms->getError());
}
$this->set('success', ucwords('event succcesfully added!'));
}
}
$this->Cms->query function:
public function query($query, $attributes = array(), $singleResult = 0) {
echo $query;
$stmt = $this->dbc->prepare($query);
if(!empty($attributes)){
echo'<pre>';
print_r($attributes);
echo'</pre>';
foreach($attributes as $values){
if(empty($values) || $values) { $values = 'not provided'; }
if($values == NULL) { $values = '0'; }
echo $stmt->bindParam('?', $values);
echo'<pre>';
$stmt->debugDumpParams();
echo'</pre>';
}
}
$success = $stmt->execute();
return $success;
}

PHP - Avoiding nested if statements - cleaner way to code this

Assume that I am creating a registration form. I have code like the below and it is hard to manage because of all the nested if statements.
I want to know the cleanest and easiest to follow way to write code that functions similarly to what I have below.
EDIT: People have told me that I can move the empty($_POST['email']) to the validation functions. I can't do that because I need to know 1) whether user has posted data or not, and 2) whether the data user posted is valid.
For example, when the user first goes to the registration page, they have not posted any data so $_POST['email'] will generate PHP warnings because they don't exist. That's why I check whether data has been posted before I validate.
Does this make sense?
function validate_email($str) {
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
function validate_password($str) {
$str = trim($str);
if(strlen($str) < 5 || strlen($str) > 70) {
return false;
} else {
return $str;
}
}
$email = false;
$password = false;
$errorMessage = false;
if(!empty($_POST['email'])) {
$email = validate_email($_POST['email']);
if($email) {
if(!empty($_POST['password'])) {
$password = validate_password($_POST['password']);
if($password) {
createNewUser($email,$password);
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "Email address is invalid";
}
} else {
$errorMessage = "Email address is invalid";
}
if($errorMessage) echo $errorMessage;
Whenever you have nested if()s you can flip the logic "inside out":
if (A)
if (B)
if (C)
final()
change to:
if (!A) return
if (!B) return
if (!C) return
final()
In your case instead of returning you could throw an exception.
try {
validateAndCreateNewUser();
}
catch(ValidationError $e) {
display($e->getMessage());
}
You don't need the empty checks at that point, move them to the validation functions.
For example:
function validate_email($str) {
if(empty($str)) {
return false;
}
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
$email = validate_email($_POST['email']);
if($email) {
// your code
}
This is a bit cleaner:
function validate_email($str) {
if (empty($str)) return false;
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
function validate_password($str) {
if (empty($str)) return false;
$str = trim($str);
if(strlen($str) < 5 || strlen($str) > 70) {
return false;
} else {
return $str;
}
}
$email = false;
$password = false;
$errorMessage = false;
$email = validate_email($_POST['email']);
if($email) {
$password = validate_password($_POST['password']);
if($password) {
createNewUser($email,$password);
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "Email address is invalid";
}
if($errorMessage) echo $errorMessage;

Categories