I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim
Related
Almost 2 days my computer doesn't want to insert data in my DB, tried to change a lot in code but still not works. (and deleted ` - and nothing changed). Could you suggest what is the reazon?
<?php
include '../db.php';
try {
$stmt = $dbh->prepare(" INSERT INTO `users` (`login`,`password`) VALUES (:login, :password) ");
$stmt->bindParam(':login', $login );
$stmt->bindParam(':password', $password );
$_POST['login'] = $login;
$_POST['password'] = $password;
$stmt->execute();
}
catch (exeption $e) { // Если ошибка - показать сообщение об ошибке
echo $e->getMessage();
}
echo "\nPDO::errorCode(): ", $dbh->errorCode();
echo " ";
$rows = $stmt->fetchAll();
$num_rows = count($rows);
echo $num_rows;
/*header("location:../auth.php");*/
?>
Returns PDO::errorCode(): 00000 (thats fine), but it returns 0 rows! Maybe that's the reason
And my db.php file:
<?php
try { //Connecting to db via login and password
$user = 'mydatabases';
$pass = '1234';
$dbh = new PDO('mysql:host=localhost;dbname=dbname', $user, $pass);
}
catch (exeption $e) { //if any mistakes show message of error
echo $e->getMessage();
}
?>
In my DB was 2 extra columns I wanted them to be empty (they didnt fill when user register), that was the reason why code didnt work and didnt send me any error messages
I'm trying to learn to convert a PHP login page to use prepared SQL statements with parameters versus just using standard script to protect from SQL injection. Its for a security class and not a programming class and my PHP is weak and be will evident. I can't figure out why I'm not getting any results from the execution. Its using PDO, and I've switch from bindParam to bindValue as suggested on other topics, but I still get a black page from the login.
My db connection is working, and I think my SQL statement and parameters are correct. I really believe the problem is in retrieving the results. Can anyone help why I can get a row count? I've also tried with $stmt->count_rows
<html>
<body>
<?php
$db_hostname = 'localhost';
$db_username = 'testuser';
$db_password = '1234';
$db_dbname = 'testdb';
$db_tablename = 'users';
$db_conn_str = "mysql:host=" . $db_hostname . ";dbname=" . $db_dbname;
try {
$db = new PDO($db_conn_str, $db_username, $db_password);
$stmt = $db->prepare("Select * from users where login = ? and passwd = ?");
$stmt->bindValue(1, $_POST['username']);
$stmt->bindValue(2, $_POST['password']);
$stmt->execute();
$stmt->store_result();
$result = $stmt->fetchAll();
$num = $result->rowCount();
$stmt->close();
}
catch (PDOException $e) {
echo "Error in PDO: " . $e->getMessage();
}
if ($num == 0) {
echo "login failed! <br />";
} else {
$name = $result->fetchColumn(0);
echo "Welcome, $name!<br />";
}
?>
A few issues.
Syntax error after $db_hostname='localhost'
PDO does not have a store_result() method, that's a mysqli method.
Turn off emulated prepared querys. ATTR_EMULATE_PREPARES
You need to also tell PDO to throw Exceptions else it wont ERRMODE_EXCEPTION
Also $result->fetchColumn(0); will fetch the first column so presuming that id your welcome message would say Welcome, 1.
Just count fetchAll() instead of rowCount().
Don't forget htmlentities() to protect against stored XSS
Below is changed code:
<?php
$db_hostname='localhost';
$db_username='testuser';
$db_password='1234';
$db_dbname='testdb';
$db_tablename='users';
$db_conn_str="mysql:host=" . $db_hostname . ";dbname=" . $db_dbname;
try {
$db = new PDO($db_conn_str, $db_username, $db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $db->prepare("SELECT * FROM users WHERE login = ? AND passwd = ?");
$stmt->bindValue(1, $_POST['username']);
$stmt->bindValue(2, $_POST['password']);
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) == 0) {
echo "login failed! <br />";
} else {
echo "Welcome, ".htmlentities($result[0]['name'])."!<br />";
}
$stmt->close();
} catch (PDOException $e) {
echo "Error in PDO: " . $e->getMessage();
}
?>
You should also look into using password_* based functions instead of storing your passwords as plaintext.
Hope it helps.
I've been trying to create a php login system but I can't make it work as if I try to login with valid username and password it will say "fail". I've using this technique before and was successful but this time I can't make it work.
Code:
<?php
$username=$_POST['username'];
$password=$_POST['password'];
$conn = new PDO("mysql:host=localhost;dbname=login" ,'root','');
if (!$conn){
die("Not connected". mysqli_connect_error());
}else {
echo "Connection sucessfull";
echo "</br>";
}
$sql = "select * from details where Username=$username and Password=$password";
$stmt=$conn->prepare($sql);
$stmt->bindparam("Username",$username,PDO::PARAM_STR);
$stmt->bindparam("Password",$password,PDO::PARAM_STR);
$stmt->execute();
$num = $stmt->rowCount();
if ($num>0){
echo "You are logged in";
}else {
echo "fail";
}
Thanks
Your statement should go like this:
$stmt= $conn->prepare("SELECT * FROM `details`
WHERE `Username`=:username AND `Password`=:password");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
Note:
According to php.net PDOStatement::rowCount() returns the number of
rows affected by the last DELETE, INSERT, or UPDATE statement executed
by the corresponding PDOStatement object.
So for counting the number of rows returned by select statement, you can use fetchAll():
if (count($stmt->fetchAll()) > 0) {
echo "You are logged in";
}else {
echo "fail";
}
And for setting smart PDO connection:
try {
$db_host = '';// hostname
$db_name = '';// databasename
$db_user = '';// username
$user_pw = '';// password
$conn = new PDO('mysql:host='.$db_host.'; dbname='.$db_name, $db_user, $user_pw);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$conn->exec("SET CHARACTER SET utf8");
}catch (PDOException $err) {
echo "harmless error message if the connection fails";
$err->getMessage() . "<br/>";
file_put_contents('PDOErrors.txt',$err, FILE_APPEND);//log errors
die(); // terminate connection
}
I've formatted your code and it should work now. You cannot mix mysqli_* with PDO.
$conn = new pdo("mysql:host=localhost;dbname=login;", 'root', '');
if ($conn->connect_error) {
die("Not connected" . $conn->connect_error);
}
echo "Connection successful<br/>";
$sql= "select * from details where Username=:username and Password=:password";
$result = $connection->prepare($sql);
$result->bindParam(":username" ,$_POST['username']);
$result->bindParam(":password" ,$_POST['password']);
$result->execute();
$num=$result->fetchColumn();
if($num > 0){
header("location:index.php");
}else{
header("location:login.php");
}
try {
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM us WHERE username='$suser' and password='$shashpass'"; // SQL Query
$conn->exec($sql);
Thats some of my code, how do I make it so if suser and shashpass are correct it can
execute some code, else it executes other code
This won't work either
<?php
try
{
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password"); $query->bindParam(':user',$suser);
$query->bindParam(':password',$shashpass); $query->execute(); $result = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){ } else { } }
catch(PDOException $e) {
echo $sql . $e->getMessage();
}
You don't pre-hash the password when verifying it. Instead you SELECT the password hash from that user (if it exists) and then use password_verify() to verify that it's correct based on the plain text password sent by the web form.
$stmt = $conn->prepare("SELECT password FROM us WHERE username=?");
$stmt->execute([$suser]);
if ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (password_verify($plain_text_password, $user['password'])) {
// Successful login
}
else {
// Valid user, but invalid password
}
}
else {
// User doesn't exist
}
If you're not using password_hash() and password_verify(), You're Doing It Wrong™.
you are using PDO in wrong way , you need to use prepared statements in PDO to be secure from mysql injections, try to use the code below:
try {
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password");
$query->bindParam(':user',$suser);
$query->bindParam(':password',$shashpass);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
// user is in database
} else {
// user is not there
}
exec will return the number of affected rows so:
$rows = $conn->exec($sql);
if($rows > 0){
//suser and shashpass are correct
}else{
//suser and shashpass are incorrect
}
//Use below PDO code
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
$sql = "SELECT * FROM us WHERE username='$suser' and password='$shashpass'";
// SQL Query
$conn->exec($sql);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I had code that used mysql_connect which I understand is now deprecated to I switched to the following code (I'm working locally):
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$DBusername = 'admin';
/*** mysql password ***/
$DBpassword = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
But this now means that a function of mine breaks:
$result = mysql_num_rows($query);
Because, following the script back, the connection is not working. There is something up with my PDO connection script but I do not understand what I have done wrong. The details are correct for logging into phpMyAdmin on localhost.
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
PDO is entirely independent from the mysql extension, you will have to update your function calls as well. mysql_query for example should be a combination of prepare and execute.
As a note: Please please use Prepared Statements, your example query is completely insecure.
As an example was requested:
// initialize PDO
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
// Prepare a query
$sql = "SELECT COUNT(*) AS count
FROM users
WHERE username = ?
LIMIT 1";
$statement = $dbh->prepare($sql);
// execute the query
$statement->execute(array($username));
// retrieve the first row
$row = $statement->fetch();
if ($row['count']) echo 'The user exists';
else echo 'The user does not exist';