简体   繁体   中英

Pass a $_POST value into a function parameter with a PDO variable

I have setup a pdo connection and pass that as a variable into a function. This all works fine and the function returns correctly. If I run the function in a conditional statement with the PDO variable and a name it runs correctly - if name is in database it echos correctly if not then it also echos correctly. What I want to do is to pass the value of a form post to the function so that it checks to see if it exists in the database. Here is my code:

The function checks to see if the column count is one.

function user_exists($pdo, $username) {
$stmt = $pdo->prepare('SELECT COUNT(uid) FROM users WHERE username =    :username');
$stmt->execute(['username' => $username]);
$result = $stmt->fetchColumn();
return ($result == 1);
}

If the admin user exists in the database echo 'exists' - Just for testing.

if(user_exists($pdo,'admin') == true) {
echo "exists";
} else {
echo "doesnt exist";
}

Checks to see of both fields have been entered then I want it to check if the username entered is in the database, but I am doing something wrong.

if(!empty($_POST) === true) {
$username = $_POST['username'];
$pwood = $_POST['password'];
if(empty($username) === true || empty($pwood) === true) {
echo "You need to enter a username and password";
} else if (user_exists($pdo,$_POST['username']) == false){
echo 'We can\'t find that username. Please try again or register';
}
}

Better don't compare with bool values, just use

//...see below
require_once('UserRepository.php');
$ur = new UserRepostory($pdo);

if(!empty($_POST)) {
    if (empty($username) || empty($pwood)) {
        // something
    } else if (!$ur->exists($_POST['username'])) { // your user_exists($pdo, $username) works fine, too
        // something else
    }
}

Especially the initial if(!empty($_POST) === true) { is hard to read and lead to errors 'cause of misunderstood operator priority.

Update based on the comments above, here is an example with a class:

// UserRepository.php
class UserRepository {
    private $pdo;

    // '\PDO' instead of 'PDO', see PHP Namespacing
    public function __construct (\PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function exists($username)
    {
        $sql = 'SELECT COUNT(uid) FROM users WHERE username = :username');
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(['username' => $username]);
        $result = $stmt->fetchColumn();

        return (bool) $result;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM