Mysqli to PDO conversion - php

I recently started using PDO a few days ago and am changing all my mysqli code but I seem to have hit a brick wall. Now this code worked beautifully when I was using mysqli, but now I can't seem to print out the result. This code basically takes the input value of password, and that of the hashed password in the database, matches them and if both are equal then the user will be logged in. My problem is that I can't seem to find a way to get the password from my database. Any help would be much appreciated. Thank you.
<?php
session_start();
$user = "root";
$pass = "";
$mcon = new PDO('mysql:host=localhost;dbname=rabbit_users', $user, $pass);
try {
$mcon = new PDO('mysql:host=localhost;dbname=rabbit_users', $user, $pass);
$mcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
//prepare statement
$password = $_POST['password'];
$stmt = $mcon->prepare("SELECT `password` FROM members WHERE password=:password");
$stmt->bindParam(":password", $_POST['password']);
$stmt->execute();
//get_result
$data_array = $stmt->fetchAll();
$stmt->fetch(PDO::FETCH_ASSOC);
//echo passwords
print 'Password from form: ' . $password . '<br />';
print 'Password from DB: ' . $data_array['password'] . '<br />';
//verify password
if (password_verify($password, $data_array['password'])) {
print 'success';
exit();
}else{
print 'Try again m9';
exit();
}

fetchAll returns an array containing all of the result set rows. So you can access to password with $data_array[0]['password'] if you used it.
You may want use fetch instead.
$data_array = $stmt->fetch(PDO::FETCH_ASSOC);

Related

Doesn't insert data in DB

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

Coverting PHP login script to use prepared statements

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.

PHP bindParam not working - blindValue is not the solution

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

PHP login script always returns "login failed"

I have to give users the ability to log in for an assignment. At first, it seemed to me this script was simple enough to work, but everytime I try to log in with an existing account it gives me the "login failed" message. I don't know where my mistake lies. It's a PostgreSQL database, I'll enclose an image of it below.
<?php
require 'databaseaccess.php';
try {
$conn = new PDO('pgsql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME,DB_PASSWORD);
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "\n";
phpinfo();
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$tablename = "users";
// sql-injection counter
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$qry = $conn->prepare("SELECT * FROM $tablename WHERE userid = :username and userpass = :password");
$qry->bindParam(':username', $username, PDO::PARAM_STR, 16);
$qry->bindParam(':password', $password, PDO::PARAM_STR, 16);
$qry->execute();
$result = pg_query($qry);
$count = pg_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count == 1) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
header("location:logingelukt.php");
} elseif ($count = -1) {
echo "there has been an error";
} else{
print $count;
echo "login failed";
}
?>
I have no problems connecting to the database, so that's not an issue, it's just that it always sees $count as something else than zero. Another oddity is that the print $count command doesn't output anything.I use the account I made with postgresql outside of the page, which is just admin:admin. Also, I'm sure the right variables are getting passed from the form.
EDIT: After using var_dump($result), as advised by kingalligator, it seems that $result is indeed NULL, thus empty. I'm gonna try using fetch() instead of pg_query().
I think the issue is that you're mixing PDO and pg_ functions.
Replace:
$result = pg_query($qry);
$count = pg_num_rows($result);
With:
$result = $qry->fetchAll();
$count = count($result);
PDO Function reference can be found here: http://www.php.net/manual/en/class.pdostatement.php
Have you confirmed that you're actually getting data returned from your query? Try this:
var_dump($result);
To ensure that data is being returned from your query. You can still have a successful connection to a database, yet have a query that returns nothing.
You probably should check your column userid at WHERE clause. I don't know the table columns, but is strange that 'userid' has the name of the user in:
"SELECT * FROM $tablename WHERE userid = :username and userpass = :password"
Maybe it is causing the problem.

Login users/start session with PDO

Im trying to create a login section on my website using PDO.
So far I've the following...
config.php
// Connect to DB
$username = 'user#site.co.uk';
$password = 'pass';
try {
$conn = new PDO('mysql:host=localhost;dbname=db', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
header.php
// DB Config
include '/assets/config.php';
// User Session
$login = 'liam';
$pass = 'password';
$sth = $conn->prepare("SELECT * FROM access_users WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, $pass);
$sth->execute();
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
}
?>
My browser doesn't display the page however, and when I view my source theres no data contained within, can anybody see where im going wrong?
try this:
// User Session
$login = 'liam';
$pass = 'password';
$sth = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$sth->execute(array(":username" => $login,":password" => $pass));
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
echo $sth->rowCount();
}
make sure you have username "liam" and pass "password" in the database
You have set PDO::ERRMODE_EXCEPTION. This means, you should wrap your statements in a try/catch block and test execute()s return code:
try {
$sth = $conn->prepare("SELECT * FROM access_users WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, $pass);
if (!$sth->execute()) {
$info = $sth->errorInfo();
echo 'Error: ' . $sth->errorCode() . ' (' . $info[2] . ")\n";
} elseif ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
}
} catch (PDOException $e) {
echo 'Exception: ' . $e->getMessage() . "\n";
}
and put some trace statements in, of course.

Categories