Luci Poienariu Luci Poienariu - 2 months ago 6
PHP Question

How can I get a string from a function

So, this is my code:

class Functions{
public static function login($email,$password){
$email = $_GET['email'];
$password = $_GET['password'];
if(isset($_GET['submit']) AND isset($email) AND isset($password)){
$password = md5($password);
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$_SESSION['nume'] = $row["name"];
$_SESSION['uid'] = $row["id"];
$_SESSION['admin'] = $row["admin"];
$_SESSION['email'] = $row["email"];
$_SESSION['points'] = $row["points"];
}else{
$errortxt = "Invalid Login Credentials";
$error = true;
}
}
return $error;
}
}


In my HTML file I'm calling for the function like this:

Function::login($email,$password);


But I'm wondering how can I get the $errortxt string to echo in the HTML file.

Thanks!

Answer

You just need a simple fix:

class Functions{
public static function login($email,$password){
    $response['error'] = false;
    $response['errortxt'] = "";
    $email = $_GET['email'];
    $password = $_GET['password'];
    if(isset($_GET['submit']) AND isset($email) AND isset($password)){
        $password = md5($password);
        $sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $_SESSION['nume'] = $row["name"];
            $_SESSION['uid'] = $row["id"];
            $_SESSION['admin'] = $row["admin"];
            $_SESSION['email'] = $row["email"];
            $_SESSION['points'] = $row["points"];
        }else{
            $response['error'] = true;
            $response['errortxt'] = "Invalid Login Credentials";
        }
    }
    return $response;
}
}

And you need to call it this way:

$fnCallStatus = Function::login($email,$password); //Now you have the response;
if($fnCallStatus['error']) //we have an error
{
    echo $fnCallStatus['errortxt']; //we print the message
}