mholberger
mholberger

Reputation: 357

simple user_exists function using PDO connect to mysql

I'm still in the early learning stages, banging my head against walls looking for clues. Iv been reading the manual to no avail.

I'm building a user log in system based on the phpAcadamy tutorial 'Register & Login' (part 5-2). They use mysql_connect() in the tutorial, but I am using a PDO connection for mysql.

I am making my first function, user_exists(), which returns a true or false depending on if the username is in the database. it queries for the user_id (an auto-incremented value in the db) when username = the POSTed $username then depending if the user_id == 1, returns a true or false.

here is my testing code: the if statement at the bottom should test the function above it.

i get a Fatal error: Call to a member function query() on a non-object

    <?php

    $host       = "localhost";
    $username   = "mholberg_skroovy";
    $password   = "omitted";
    $dbname     = "mholberg_skroovytest";


$db = new PDO("mysql:host={$host};dbname={$dbname};", $username, $password);


function user_exists($username) {
    $query = $db->query("SELECT `users`.`user_id` FROM `users` WHERE `username` = '$username'");
    return(mysql_result($query, 0) == 1) ? true : false;                //???
}



if (user_exists('junkomatic') === true) {
    echo 'exists';
}
die();
?>

Upvotes: 0

Views: 401

Answers (1)

Phil
Phil

Reputation: 164910

You need to bring your connection object ($db) into the function's scope.

Here's an example

function user_exists(PDO $db, $username) {
    $stmt = $db->prepare('SELECT COUNT(1) FROM `users` WHERE `username` = ?');
    $stmt->bindParam(1, $username);
    $stmt->execute();
    return (bool) $stmt->fetchColumn();
}

$host       = "localhost";
$username   = "mholberg_skroovy";
$password   = "omitted";
$dbname     = "mholberg_skroovytest";

$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8",
    $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (user_exists($db, 'junkomatic')) {
    echo 'exists';
}

Upvotes: 1

Related Questions