PHP does not return database result

Asked

Viewed 675 times

1

Hello,

I have the following function:

function makeLogin($user, $pass) {
    $pdo = new PDO("mysql:host=".HOSTNAME.";dbname=".DATABASE.";charset=utf8;", USERNAME, PASSWORD);
    $sql = $pdo->prepare("SELECT user, pass FROM users WHERE user = :user AND pass = :pass");
    $sql->bindParam(":user", $user);
    $sql->bindParam(":pass", $pass);
    $sql->execute();
    $users = $sql->fetchAll(PDO::FETCH_ASSOC);
    if(count($users) <= 0) {
        return "false";
    } else {
        return "true";
    }
}

If found in the database, user and password, PHP returns true, otherwise false, but does not find user and password.

I am using the following SQL:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user` varchar(36) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pass` varchar(36) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;

INSERT INTO `users` (`id`, `user`, `pass`) VALUES
(1, 'admin', 'admin');

Example of use:

if(makeLogin($_POST['usuario'], $_POST['senha']) == 'true') {
        setcookie('logged', true,  time() + 86400);
} else {
    setcookie('logged', false,  time() + 86400);
}

The post is admin and admin.

Thanks in advance.

  • 1

    always returns false?

  • 2

    Put the code of form only the User and Password fields and also the function call makeLogin.

  • 1

    Have you tried debugging variables $user and $pass?

  • 1

    See if any error appears with this code: if(!$sql->execute()){&#xA; print_r($sql->errorInfo());&#xA;}

  • 1

    in which server are you running? has server that only accepts the queries with those simple quotes SELECT `user`, `pass` FROM `users` WHERE `user` = :user AND `pass` = :pass")

1 answer

-1

Look I tested your code here and it worked.

If you are using your code on the hosting server check that it is not in the phpmymadmin style syntax

For example, I went through the same problem the other day.

My query was correct but did not bring results, so I decided to put those simple quotes(`) and guess what? It worked!

My suggestion

Change:

$sql = $pdo->prepare("SELECT user, pass FROM users WHERE user = :user AND pass = :pass");

For:

$sql = $pdo->prepare("SELECT `user`, `pass` FROM `users` WHERE `user` = :user AND `pass` = :pass");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.