PDO reads the database, but does not log into system - php

I currently have a login system, which I would like to convert to PDO from Mysqli.
I currently have a website with a database attached with phpMyAdmin/MySQL.
I tried to convert everything and I will now show you the LOGIN.php part of the system since I haven't touched the signup part yet.
This is what I have.
LOGIN.INC.PHP
<?php
require_once 'dbh.inc.php';
try {
$handler = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch(PDOException $e){
echo $e->getName();
die();
}
//first we start a session
session_start();
//We then check if the user has clicked the login button
if (isset($_POST['submit'])) {
//Then we require the database connection
//require_once 'dbh.inc.php';
//And we get the data from the login form
$name = $_POST['name'];
$password = $_POST['password'];
//Error handlers
//Error handlers are important to avoid any mistakes the user might have made when filling out the form!
//Check if inputs are empty
if (empty($name) || empty($password)) {
header("Location: ../index.php?login=empty");
exit();
}
} else {
$stmt = $db->prepare("SELECT * FROM users WHERE user_name=:name");
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if ($stmt->execute()) {
header("location: ../index.php?login=error");
exit();
} else {
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//de-hashing the password
$hashedpasswordCheck = password_verify($password, $row['user_password']);
if ($hashedpasswordCheck == false) {
header("location: ../index.php?login=error");
exit();
} elseif ($hashedpasswordCheck == true) {
//Log in the user here
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_name'] = $row['user_name'];
header("location: ../index.php?login=success");
exit();
}
} else {
header("location: ../index.php?login=error");
exit();
}
}
}
DBH.INC.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "loginsystem";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$stmt = $conn->prepare("SHOW DATABASES;");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
print_r($result);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$conn = null;
When I try to login I get redirected to this url:
http://localhost/php44/includes/login.inc.php
and receive this printed message/error.
Array ( [0] => Array ( [Database] => imgupload ) [1] => Array ( [Database] => information_schema ) [2] => Array ( [Database] => loginsystem ) [3] => Array ( [Database] => mysql ) [4] => Array ( [Database] => performance_schema ) [5] => Array ( [Database] => phpmyadmin ) [6] => Array ( [Database] => test ) )
What should I do to fix this, so that my login works?

Your code is vulnerable to Html Elements Injection and session fixation attack. I have implemented strip_tags() to prevents html element injection attack and have also implemented session_regenerate_id(); to prevent session fixation attack.
Again since you are login, you only need to initialize session as soon as username and password is verified.
As for me, I prefer using PDO array method. Anyway I have provided two solution. I first work on your code and then modify it were appropriate. Ensure that database credentials is okay
Your code
<?php
//db connect starts
$db = new PDO (
'mysql:host=localhost;dbname=loginsystem;charset=utf8',
'root', // username
'' // password
);
//We then check if the user has clicked the login button
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$password = $_POST['password'];
if ($name =='' && $password =='') {
header("Location: ../index.php?login=empty");
exit();
}
$stmt = $db->prepare("SELECT * FROM users WHERE user_name=:name");
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
if( $count == 1 ) {
$row = $stmt->fetch();
if(password_verify($password,$row['password'])){
echo "Password verified and ok";
// initialize session if things where ok.
session_start();
//Prevent session fixation attack
session_regenerate_id();
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_name'] = $row['user_name'];
header("location: ../index.php?login=success");
exit();
}
else{
echo "Wrong Password details";
}
}
else {
echo "User does not exist";
}
}
?>
my code
<?php
//if (isset($_POST['submit'])) {
if ($_POST['name'] !='' && $_POST['password']) {
//connect
$db = new PDO (
'mysql:host=localhost;dbname=loginsystem;charset=utf8',
'root', // username
'' // password
);
$name = strip_tags($_POST['name']);
$password = strip_tags($_POST['password']);
if ($name == ''){
echo "Username is empty";
exit();
}
if ($password == ''){
echo "password is empty";
exit();
}
$result = $db->prepare('SELECT * FROM users where user_name = :name');
$result->execute(array(
':user_name' => $name));
$count = $result->rowCount();
if( $count == 1 ) {
$row = $result->fetch();
if(password_verify($password,$row['password'])){
echo "Password verified and ok";
// initialize session if things where ok.
session_start();
//Prevent session fixation attack
session_regenerate_id();
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_name'] = $row['user_name'];
header("location: ../index.php?login=success");
exit();
}
else{
echo "Wrong Password details";
}
}
else {
echo "User does not exist";
}
}
?>

I've made some fixes and added comments in to explain what changed:
LOGIN.INC.PHP
<?php
//First we start a session
session_start();
//Then we require the database connection
require_once 'dbh.inc.php';
// Removed the extra database connection here.
//We then check if the user has clicked the login button
if (isset($_POST['submit'])) {
//And we get the data from the login form
$name = $_POST['name'];
$password = $_POST['password'];
//Error handlers
//Error handlers are important to avoid any mistakes the user might have made when filling out the form!
//Check if inputs are empty
if (empty($name) || empty($password)) {
header("Location: ../index.php?login=empty");
exit();
}
//Removed extra 'else' here.
$stmt = $conn->prepare("SELECT * FROM users WHERE user_name=:name"); // Changed $db to $conn to use the connection from DBH.INC.PHP
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if (!$stmt->execute()) { // Added the ! to say "if this doesn't work, redirect to error"
header("location: ../index.php?login=error");
exit();
} else {
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//de-hashing the password
$hashedpasswordCheck = password_verify($password, $row['user_password']);
if ($hashedpasswordCheck == false) {
header("location: ../index.php?login=error");
exit();
} else if ($hashedpasswordCheck == true) {
//Log in the user here
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_name'] = $row['user_name'];
header("location: ../index.php?login=success");
exit();
}
} else {
header("location: ../index.php?login=error");
exit();
}
}
}
DB.INC.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "loginsystem";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
// Removed the query and print of the databases
}
catch(PDOException $e) {
echo $e->getMessage();
}
// Removed the $conn=null to keep the connection we just set up.

Related

Check usertype at login (php)

I made a website with registration/login system and I want to make an admin panel as well. I gave my account admin usertype (mysql) but I don't know how to check the usertype at login. This is my authenticate code that checks logins (echos have texts in Hungarian don't care about that):
session_start();
$DATABASE_HOST = 'sql305.epizy.com';
$DATABASE_USER = 'epiz_25331636';
$DATABASE_PASS = 'q1SI3G8B0s';
$DATABASE_NAME = 'epiz_25331636_accounts';
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
if ( !isset($_POST['username'], $_POST['password']) ) {
exit('Felhasználónév és jelszó is szükséges!');
}
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
if (password_verify($_POST['password'], $password)) {
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
header('Location: home.php');
} else {
echo "<script type='text/javascript'>alert('Helytelen jelszó');
window.location='index.html';
</script>";
}
} else {
echo "<script type='text/javascript'>alert('Helytelen felhasználónév');
window.location='index.html';
</script>";
}
$stmt->close();
}
?>
Assuming you have a usertype field for each user, which contains "admin" for administrators, you can do the following:
if ($stmt = $con->prepare('SELECT id, password, usertype FROM accounts WHERE username = ?')) {
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password, $usertype);
$stmt->fetch();
if (password_verify($_POST['password'], $password)) {
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
if($usertype == "admin"){
header('Location: adminpanel.html')
} else {
header('Location: home.php');
}
} else {
echo "<script type='text/javascript'>alert('Helytelen jelszó');
window.location='index.html';
</script>";
}
}
And like already mentioned, please change the credentials as soon as possible, if they are in use.

How to modify a Login System in msqli query to PDO? [duplicate]

This question already has an answer here:
How to convert MySQL code into PDO statement?
(1 answer)
Closed 8 months ago.
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'");
if( $result->num_rows == 0 ){
// User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error-login.php");
} else{ // User exists
$user = $result->fetch_assoc();
if( password_verify($_POST['password'], $user['password'])){
$_SESSION['email'] = $user['email'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['last_name'] = $user['last_name'];
$_SESSION['active'] = $user['active'];
$_SESSION['logged_in'] = true;
header("location: riscar.php");
} else {
$_SESSION['message'] = "You have entered wrong password, try again!";
header("location: error-login.php");
}
}
}
I need to modify this code above to PDO. I tried to make some changes:
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', null);
define('DB_CHARSET', 'utf8');
define('DB_DATABASE', 'publicacoes');
$conn = new PDO('mysql:host=' . DB_HOSTNAME . ';dbname=' . DB_DATABASE . ';charset=' . DB_CHARSET . ';', DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = $conn->prepare("SELECT * FROM users WHERE email = :email"); ###
$result->execute([':email' => $_POST['email']]); ###
if( $result->num_rows == 0 ){
// User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error-login.php");
} else{ // User exists
$user = $result->fetch_assoc();
if( password_verify($_POST['password'], $user['password'])){
$_SESSION['email'] = $user['email'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['last_name'] = $user['last_name'];
$_SESSION['active'] = $user['active'];
$_SESSION['logged_in'] = true;
header("location: riscar.php");
} else {
$_SESSION['message'] = "You have entered wrong password, try again!";
header("location: error-login.php");
}
}
}
But it's not working, I got the errors:
1 - Undefined variable: result.
2 - Fatal error: Uncaught Error: Call to a member function execute() on null.
It gets the same error if i change &result to $email.
What's wrong with the code? I'm not familiar with MYSQLi. I'm thinking that maybe i need to change all the code on this login system. I need to modify it to PDO.
Firstly, you don need to escape_string with pdo prepared statement.
Secondly, you should change your database connection compatible with pdo along with the pdo attributes PDO::ATTR_ERRMODE & PDO::ERRMODE_EXCEPTION so that you can at least catch pdo errors and exceptions. You can add other error handling attributes too in your connection statement. See http://php.net/manual/en/pdo.error-handling.php for more details.
$DATABASESERVER = "YOUR_DATABASE_SERVER_NAME";
$DATABASENAME = "YOUR_DATABASE_NAME";
$DATABASEUSERNAMNE = "YOUR_DATABASE_USERNAME";
$DATABASEPASSWORD = "YOUR_DATABASE_PASSWORD";
try {
$DatabaseCon = new PDO("mysql:host=$DATABASESERVER; dbname=$DATABASENAME", $DATABASEUSERNAMNE, $DATABASEPASSWORD);
$DatabaseCon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "$DatabaseCon-> failed: " . $e->getMessage();
}
and finally you can replace your code with:
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = trim($_POST['email']);
try{
$Query = "SELECT * FROM users WHERE email=:email";
$statement = $DatabaseCon->prepare($Query);
$statement->bindValue(':email', $email);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
$RowCount = $statement->rowCount();
}
catch (PDOerrorInfo $e){
die('QuerySCD Error '.$e->getMessage());
}
if( $RowCount == 0 ){
// User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error-login.php");
} else{ // User exists
if( password_verify($_POST['password'], $user['password'])){
$_SESSION['email'] = $user['email'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['last_name'] = $user['last_name'];
$_SESSION['active'] = $user['active'];
$_SESSION['logged_in'] = true;
header("location: riscar.php");
} else {
$_SESSION['message'] = "You have entered wrong password, try again!";
header("location: error-login.php");
}
}
}
//close database connection
$DatabaseCon-> = NULL;
However, you can also use positional place holder & bindParam method in your pdo syntax. See manual for more details.
All the best.
You're code can be written like this using my PDO wrapper class called GrumpyPDO.
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//select row of results where email is posted email
//$db must be set prior to this
$user = $db->row("SELECT * FROM users WHERE email=?", [$_POST['email']]);
if(!empty($user)) { //user exists if $result is not empty
//everything from here on is the same
if(password_verify($_POST['password'], $user['password'])) {
$_SESSION['email'] = $user['email'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['last_name'] = $user['last_name'];
$_SESSION['active'] = $user['active'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
header("location: riscar.php");
} else {
$_SESSION['message'] = "You have entered wrong password, try again!";
header("location: error-login.php");
}
} else {
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error-login.php");
}
}

Php project login error

Recently i developed a small school management software everything is fine in localhost but when i move the file to online server and try to login my (role) than it shows me a message and change the url mydomain/authenticate.php
The bizedu.co.in page isn’t working
bizedu.co.in is currently unable to handle this request.
500
Authenticate.php code here-
<?php
require 'connection.php';
ob_start();
session_start();
$id = "";
$password = "";
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
if (isset($_POST['password'])) {
$password = $_POST['password'];
}
echo $id . " : " . $password;
$q = 'SELECT * FROM account WHERE id=:id AND password=:password';
$query = $conn->prepare($q);
$query->execute(array(':id' => $id, ':password' => $password));
if ($query->rowCount() == 0) {
header('Location: index.php?err=1');
} else {
$row = $query->fetch(PDO::FETCH_ASSOC);
session_regenerate_id();
$_SESSION['sess_user_id'] = $row['id'];
$_SESSION['sess_username'] = $row['username'];
$_SESSION['sess_userrole'] = $row['role'];
echo $_SESSION['sess_userrole'];
session_write_close();
if ($_SESSION['sess_userrole'] == "admin") {
header('Location: school_admin_home1.php');
} elseif ($_SESSION['sess_userrole'] == "employee") {
header('Location: school_employee_home.php');
} elseif ($_SESSION['sess_userrole'] == "parent") {
header('Location: parent_home.php');
} else {
}
}
?>
Connection.php code here-
<?php
//database credentials
define('DBHOST','localhost');
define('DBUSER','bizeduco_portal ');
define('DBPASS','password123');
define('DBNAME','bizeduco_school');
try {
//create PDO connection
$conn = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
?>
Please give me a solution.

destroying session if not set using php pdo

I have this old code that see if session is not registered to destroy it and go back to login page:
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
//if(!session_is_registered(myusername)){
//header("location:index.html");
if(isset($_SESSION['username'])) {
echo "Page seen by " . $_SESSION['username']."<br>";
$con=mysqli_connect($host,$username,$password,$db_name);
mysqli_set_charset($con, 'utf8mb4');
}
else{
session_destroy();
header("location: index.php");
}
?>
I am trying to convert this code to pdo but I can't know how to destroy the session in this method. I just stopped after writing those lines:
<?php
session_start();
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "";
try
{
$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Plus, In the following code, always when I click on login it will take me to the next page even if the username and password are incorrect:
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "";
$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username != '' && $password!=''){
try{
session_start();
$sql = "SELECT * FROM login WHERE username = :u AND password = :p LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindValue(":u", $username);
$stmt->bindValue(":p", $password);
$exec = $stmt->execute();
$count = $stmt->fetch(PDO::FETCH_ASSOC);
if((count($count)==1)){//&& password_verify($password, $count['password']
$_SESSION['username'] = $username;
header("Location: ./pages/home.php");
}
else {
header("Location: index.php");
}
}
catch(PDOException $e) {
$sql_fail = "INSERT INTO login_attempts(username, password, date_now, time_now)
VALUES (:uf, :pf, :date, now())";
$stmt_fail = $conn->prepare($sql_fail);
$stmt_fail->bindValue(":uf", $username);
$stmt_fail->bindValue(":pf", $password);
$stmt_fail->bindValue(":date", date("y-m-d"));
$exec_fail = $stmt_fail->execute();
header("Location: index.php");
echo $e->getMessage();
}
}
}
?>
I think the key to your login is that you need some little self-contained applications (functions) to break down simple tasks. See if this works better:
/classes/class.PDOConn.php
<?php
class PDOConn
{
// Create a singleton variable to store persistent connection
private static $singleton;
// Set your database credentials here
public static function connect($DB_host = "localhost",$DB_user = "root",$DB_pass = "",$DB_name = "")
{
// first check if the connection has been already set
if(empty(self::$singleton)) {
try {
$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
self::$singleton = $conn;
return self::$singleton;
}
catch (PDOException $e) {
die("connection failed");
}
}
// Return the current connection
return self::$singleton;
}
}
/functions/function.query.php
<?php
// This function will make automatic queries to your database
// It accepts a bind array as a second parameter
function query($sql = false,$bind = false)
{
// Create connection
$conn = PDOConn::connect();
// Two ways to query, with and without a bind array
if(!empty($bind) && is_array($bind)) {
$query = $conn->prepare($sql);
$query->execute($bind);
}
else {
$query = $conn->query($sql);
}
// Loop through returned values
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
// Send back array OR send back 0 (for zero results)
return (!empty($result))? $result : 0;
}
/functions/function.write.php
<?php
// This function is the same as query(), just no return array
function write($sql = false,$bind = false)
{
$conn = PDOConn::connect();
if(!empty($bind) && is_array($bind)) {
$query = $conn->prepare($sql);
$query->execute($bind);
}
else {
$conn->query($sql);
}
}
/functions/function.check_user.php
<?php
// This will check the user.
// Do not store plain text passwords
// Instead use password_hash() and password_verify()
function check_user($username,$password)
{
$query = query("SELECT * FROM `login` WHERE `username` = :u LIMIT 1",array(":u"=>$username));
if($query == 0)
return false;
return ($query[0]['password'] == $password);
}
/functions/function.AutoloadFunction.php
<?php
// This is just an autoloader for your functions
// I use it to help cut down on bulk loading of functions
function AutoloadFunction($function = false)
{
// If input is not array, just stop
if(!is_array($function))
return false;
// Set the load folder as this folder
// (all functions should be in the same folder)
$function_dir = __DIR__.'/function.';
// Loop through the array and add the function(s)
for($i = 0; $i < count($functions); $i++) {
// Function name
$addfunction = $functions[$i];
// See if function exists
if(!function_exists($addfunction)) {
$dir = $function_dir.$addfunction.'.php';
if(is_file($dir)) {
include_once($dir);
}
}
}
}
login.php
<?php
// Session start regardless
session_start();
// Check if login attempted
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
// If user or pass is empty OR there is already a session, just stop
// You may want to do a redirect here, not sure....
if(empty($username) || empty($password) || !empty($_SESSION['username']))
return false;
// Include the autoloader function
include_once(__DIR__.'/functions/function.AutoloadFunction.php');
// Maybe look into using spl_autoload_register() to autoload classes
include_once(__DIR__.'/classes/class.PDOConn.php');
// Autoload functions
AutoloadFunction(array("check_user","write","query"));
// Verify with handy-dandy function
if(check_user($username,$password)) {
$_SESSION['username'] = $username;
$location = "./pages/home.php";
}
// Write the attempt
else {
write("INSERT INTO `login_attempts` (`username`, `password`, `date_now`, `time_now`) VALUES (:uf, :pf, :date, NOW())",array(":uf"=>$username,":pf"=>$password,":date"=>date("y-m-d")));
$location = "index.php?errror=invalid";
}
// Forward
header("Location: {$location}");
exit;
}
Use the code in this link here.
You should use fetch(PDO::FETCH_NUM) so your code will be something like this:
$result = $conn->prepare("SELECT * FROM users WHERE username= :hjhjhjh AND password= :asas");
$result->bindParam(':hjhjhjh', $user);
$result->bindParam(':asas', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($rows > 0) {
header("location: home.php");
}
else{
$errmsg_arr[] = 'Username and Password are not found';
$errflag = true;
}
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: index.php");
exit();
}

No errors given and script isn't executed

As stated in the question before this, I have a registration system on my website and I am updating my mysql statements to PDO statements. I have updated all the statements and now the script runs through but it doesn't execute any of the script and doesn't give me any errors. It redirects me back to the registration.php page.
reg.php
<?php
include("sql.php");
require("includes/password.php");
session_start(); //Start session for writing
$errmsg = array(); //Array to store errors
$noterr = array();
$errflag = false; //Error flag
function UniqueID() {
include("sql.php");
$UID = rand(); //Create unique ID
$check = $db->prepare('SELECT * FROM `users` WHERE `UID` = :UID');
$UIDarray = array(
UID => $UID
);
$check->execute($UIDarray);
if($check->fetchColumn() > 0) { //Check if it exists
UniqueID(); //Redo the function
} else {
return $UID; //return the uniqueid
}
}
$UID = UniqueID(); //Unique ID
$username = ($_POST['username']); //Username
$email = $_POST['email']; //Email
password_hash($_POST['password'], PASSWORD_BCRYPT, array("cost" => 10)); //Password
password_hash($_POST['rpassword'], PASSWORD_BCRYPT, array("cost" => 10)); //Repeated Password
//Check Username
if($username == '') {
$errmsg[] = '<span style="color: red;">Where is your username?</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Check Password
if($password == '') {
$errmsg[] = '<span style="color: red;">Oops! No password!</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Check Repeated Password
if($rpassword == '') {
$errmsg[] = '<span style="color: red;">Your repeated password is missing!</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Make sure passwords match
if(strcmp($password, $rpassword) != 0 ) {
$errmsg[] = '<span style="color: red;">Passwords do not match</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Make sure username is availible
if($username != '') {
$qry = $db->prepare("SELECT * FROM `users` WHERE `Username` = :username"); //MySQL query
$params = array(
username => $username
);
$qry->execute($params);
if($qry->execute($params)) {
if($qry->fetchColumn() > 0) { //If username is in use
$errmsg[] = '<span style="color: red;">Sorry, that username is already in use</span>'; //Create error
$errflag = true; //Set flag so it says theres an error
}
$qry->closeCursor();
}
}
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
}
else
{
$errmsg[] = '<span style="color: red;">That is not what the picture displayed!</span>'; // Create error
$errflag = true; //Set flag so it says theres an error
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG'] = $errmsg; //Write errors
session_write_close(); //Close session
header("location: register.php"); //Rediect
exit(); //Block scripts
}
//Create INSERT query
$query = $db->prepare("INSERT INTO `userauthenticate`.`users`(`UID`, `Username`, `Email`, `Password`) VALUES(:UID,:username,:email,:password)");
$params2 = array(
UID => $UID,
username => $username,
email => $email,
password => $password
);
$query->execute($params2);
//Check whether the query was successful or not
if($query->execute($params2)) {
header("Location: login.php");
exit();
} else {
die("There was an error, try again later");
}
?>
sql.php
<?php
ob_start();
session_start();
//database credentials
$dbhost = 'dbhost';
$dbuser = 'dbuser';
$dbpass = 'dbpass';
$dbname = 'dbname';
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
It might be worth adding some try/catch blocks to catch any errors if there are any
//Make sure username is availible
if($username != '') {
try {
$qry = $db->prepare("SELECT * FROM `users` WHERE `Username` = :username"); //MySQL query
$params = array(
username => $username
);
$result = $qry->execute($params);
if($result) {
if($qry->fetchColumn() > 0) { //If username is in use
$errmsg[] = '<span style="color: red;">Sorry, that username is already in use</span>'; //Create error
$errflag = true; //Set flag so it says theres an error
}
$qry->closeCursor();
}
}
catch(PDOException e) {
// write the error to the log
$errmsg = $e->getMessage();
error_log('$errmsg-> '.$errmsg);
echo $errmsg;
}
}
if(isset($_POST["captcha"]) && $_POST["captcha"] !="" && $_SESSION["code"] == $_POST["captcha"])
{
}
else
{
$errmsg[] = '<span style="color: red;">That is not what the picture displayed!</span>'; // Create error
$errflag = true; //Set flag so it says theres an error
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG'] = $errmsg; //Write errors
session_write_close(); //Close session
header("location: register.php"); //Rediect
exit(); //Block scripts
}
try {
//Create INSERT query
$query = $db->prepare("INSERT INTO `userauthenticate`.`users`(`UID`, `Username`, `Email`, `Password`) VALUES (:UID,:username,:email,:password)");
$params2 = array(
UID => $UID,
username => $username,
email => $email,
password => $password
);
$result $query->execute($params2);
}
catch(PDOException e) {
// write the error to the log
$errmsg = $e->getMessage();
error_log('$errmsg-> '.$errmsg);
echo $errmsg;
}
//Check whether the query was successful or not
if($result) {
header("Location: login.php");
exit();
} else {
die("There was an error, try again later");
}
?>

Categories