Randy C
Randy C

Reputation: 47

I need help figure out why this code doesn't work

I have a simple script put together that is supposed to look into a database and find a name. If it finds the name, it's supposed to output a message saying that someone is logged in. Yes, I do know that I am not actually logging someone in at this point in the code. Session has to be called and created etc.. I am not ready for all of that just yet.

So here is what I have.

The php:

   <?php

try{
    $pdo = new PDO('mysql:host=localhost;dbname=interactive', 'root', '');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec('SET NAMEs "utf8"');
} catch (Exception $ex) {
$error = 'Failed to connect to the database <p>' . $ex->getMessage() . '</p>';
include '/includes/error.html.php';
exit();
}

$sql = 'SELECT name FROM members';
$result = $pdo->query($sql);

foreach($result as $row)
{
    $user[] = array(
        'user' => $row['name']
    );
}

if (!isset($_POST['username']))
{
    $true = TRUE;
}
if (isset($_POST['username']))
{
$username = $_POST['username'];
}
if (in_array($username, $user)){
  $username .= ' You are logged in!!';
}


include 'form.php';

. . . And here is the html: . . .

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf8">
        <title>InteractiveForm</title>
    </head>
    <body>
        <form action="" method="post">
            <input type="text" name="username">
            <input type="submit" value="Login">
        </form>
        <?php if (isset($_POST['username'])): ?>
        <?php echo $username; ?>
        <?php endif; ?>
    </body>
</html>

I've tried doing a print _r on $user, and it shows all of the names in the database as an associative array, so I thought that was good, but when I check to see if the name that I enter into the input exists, for some reason the in_array doesn't find it. If I am specific, and put in $user[0] it will find my name, but otherwise it won't.

What am I doing wrong?

Any help is greatly appreciated, especially with deep description!

Upvotes: 0

Views: 86

Answers (2)

Rasclatt
Rasclatt

Reputation: 12505

Try using a prepare->fetch->execute and couple other things notated below:

$sql    =   'SELECT name FROM members';
// Try prepare
$result =   $pdo->prepare($sql);
// Try execute
$result->execute();

// Loop with while and fetch
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
        // no key, just values
        $user[] =   $row['name'];
    }

if(isset($_POST['username'])) {
        $username = $_POST['username'];

        // Put this inside or else you will throw error on $username
        // if $_POST['username'] is not set
        if (in_array($username, $user)){
                echo strip_tags($username).' You are logged in!!';
            }
    }
else
    // Don't need to do another if, just use else here
    $true = true;

Also, as noted by Joe Love, you should use a WHERE clause in your sql instead of creating a giant array to check in. Something to think about!

EDIT: The above scenario would look something like:

$sql    =   "SELECT name FROM members where name = :username";
// Try prepare
$result =   $pdo->prepare($sql);
// Try execute with a bound parameter to guard against
// SQL injection
$result->execute(array(":username"=>$_POST['username']));

// Presumably, you should only get one hit, so you shouldn't need loop
$row = $result->fetch(PDO::FETCH_ASSOC);

if(isset($row['name'])) {
        echo strip_tags($row['name']).' You are logged in!!';
    }
else
    // Don't need to do another if, just use else here
    $true = true;

Upvotes: 1

sudhir
sudhir

Reputation: 46

  1. As pointed by sean , there seems to be an extra n in the usernname below code:

if (!isset($_POST['usernname']))

  1. Please ignore my ignorance , but the 'action' in html doesn't have any value. Is it okay ?

Upvotes: 0

Related Questions