I’ve just started messing around with php recently and I was testing my new knowledge out trying to make a simple login page using a database to store the username and password. All was going well but i’ve ran into a huge wall! For some reason my fetch method $result = $stmt->fetch(); isn’t returning any results even though if i run the sql query in phpmyadmin it returns a row just fine! Is this something to do with the way i’m getting the input from the form or the encryption?
here is my full code. Thanks guys be gentle i’m brand new to this haha
<?php
include 'inc/db.inc.php';
$link = new PDO(DB_INFO, DB_USER, DB_PASS);
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/style.css">
<script src="js/libs/modernizr-2.5.3.min.js"></script>
</head>
<body>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['register'])) {
$sql = "INSERT INTO account (account_name, account_pass) VALUES (:name, :pass)";
$stmt = $link->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':pass', $pass);
$name = $_POST["username"];
$pass = md5($_POST["password"]);
$stmt->execute();
echo "Thank you for registering!";
} else if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['login'])) {
$sql = "SELECT account_name, account_pass FROM account WHERE account_name=:name AND account_pass=:pass";
$stmt = $link->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$pass = strip_tags(md5($_POST["password"]));
$name = strip_tags($_POST["username"]);
$stmt->execute();
$result = $stmt->fetch();
print_r($result);
if(empty($name) || empty($pass)){
echo "please enter a username and password!";
} else {
if(empty($result)){
echo "yes";
} else {
echo "no";
}
}
} else {
?>
<form method="post" action="test.php">
<label for="username">Username: </label>
<input type="text" name="username" />
<label for="password">Password: </label>
<input type="password" name="password" />
<input type="submit" name="login" value="Login" />
<input type="submit" name="register" value="register" />
</form>
<?php } ?>
</body>
</html>
You’re using
$stmt->bindParamon variables that haven’t been set yet. adjust your code like so: