John Davidson

PHP function is not getting called

0 comments
Message:


I can not figure out why this isn't working it all looks fine to. The checkData function isn't being called. Any help would be greatly appreciated.


if(isset($_POST['submit'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$password = $_POST['password'];
$gender = $_POST['gender'];

//if statement that go through all the functions
if (checkData ($fname, $lname, $email, $password, $gender)) {}

//function that checks if information given is valid
function checkData($fname, $lname, $email, $password, $gender) {
$legal = true;
if (strlen($fname) < 1 || strlen($lname < 1) || strlen($password) < 8 || strlen($gender) < 1) {
$legal = false;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$legal = false;
}

return $legal;
}
}


All the variables are correctly set.



My Answer:
The issue here is that the checkData function is defined after it is called in the if statement. In PHP, functions need to be defined before they are called.

To fix this issue, you can move the checkData function definition above the if statement where it is being called. Here is the corrected code:

php
//function that checks if information given is valid
function checkData($fname, $lname, $email, $password, $gender) {
$legal = true;
if (strlen($fname) < 2 || strlen($lname) < 2 || !filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($password) < 8 || empty($gender)) {
$legal = false;
}
return $legal;
}

if(isset($_POST['submit'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$password = $_POST['password'];
$gender = $_POST['gender'];

//if statement that go through all the functions
if (checkData ($fname, $lname, $email, $password, $gender)) {
// do something if data is valid
}
}


By moving the checkData function definition above the if statement, the function will be properly defined and called when the form is submitted.

Rate this post

5 of 5 based on 3001 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us