store MySQL SELECT result in php variable using Prepared statements - php

I am trying to user prepared statements to find a user record and store the users ID in a php variable to use later on. I would like to echo the variable contents. How do I check the result using Prepared statements?
My CODE:
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overridePasswordInput = $_POST['overridePassword'];
$overrideUsernameInput = $_POST['overrideUsername'];
$roleID = '154';
$overrideUniqueID = $_POST['overrideUniqueID'];
//Not sure how to properly compare stored passwords vs password given by user...
$overridePassword = mysqli_real_escape_string($overridePasswordInput);
$overrideUsername = mysqli_real_escape_string($overrideUsernameInput);
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->bind_result($userID);
$stmt1->get_result();
if ($stmt1->get_result()) {
echo $userID;
} else {
echo 'User credentials incorrect. Please try again';
}
$stmt1->close();
//Close the Database connection.
$conn->close();
}//End If statement
Further more, this is the pre-existing code the original programmer used to authenticate users into the program:
if(!defined("noStartup")){
$scriptname = basename($_SERVER["PHP_SELF"]);
$phpbmsSession = new phpbmsSession;
//Testing for API login
if(strpos($scriptname,"api_")!==false){
if(isset($_POST["phpbmsusername"]) && isset($_POST["phpbmspassword"])){
$phpbmsSession->loadDBSettings();
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
include_once("common_functions.php");
$phpbmsSession->loadSettings($sqlEncoding);
$phpbms = new phpbms($db);
if(!$phpbmsSession->verifyAPILogin($_POST["phpbmsusername"],$_POST["phpbmspassword"],ENCRYPTION_SEED))
$error = new appError(-700,"","Login credentials incorrect",true,true,true,"json");
} else
$error= new appError(-710,"","No login credentials passed",true,true,true,"json");
} else {
$phpbmsSession->loadDBSettings($sqlEncoding);
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
$phpbmsSession->loadSettings($sqlEncoding);
include_once("common_functions.php");
$phpbms = new phpbms($db);
if(!isset($noSession))
$phpbmsSession->startSession();
if (!isset($_SESSION["userinfo"]) && $scriptname != "index.php") {
if(isset($loginNoKick)){
if(!isset($loginNoDisplayError))
exit();
} else{
goURL(APP_PATH."index.php");
}
}
}
$db->stopOnError=true;
}//end if
And the verifying function:
function verifyAPIlogin($user,$pass){
$thereturn=false;
$this->db->stopOnError = false;
$querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype
FROM users
WHERE login!=\"Scheduler\" AND login=\"".mysql_real_escape_string($user)."\"
AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\")
AND revoked=0 AND portalaccess=1";
$queryresult = $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-720,"","Error retrieving user record",true,true,true,"json");
return false;
}
if($this->db->numRows($queryresult)){
//We found a record that matches in the database
// populate the session and go in
$_SESSION["userinfo"]=$this->db->fetchArray($queryresult);
$querystatement="UPDATE users SET modifieddate=modifieddate, lastlogin=Now() WHERE id = ".$_SESSION["userinfo"]["id"];
$queryresult=# $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-730,"","Error Updating User Login Time",true,true,true,"json");
} else
$thereturn=true;
}
return $thereturn;
}
}//end loginSession class
NOTE: I have already tested that my $_POST() values are successfully coming through to my script.
EDIT:: added more code to give a better overall picture of what I'm attempting to do. Any shared tuturials on password encryption/authenticating users would be greatly appreciated.
Thank you!

As I mentioned in the comment, PHP now has a couple built in methods to handle encryption and decryption of passwords that you might find helps solve your problem:
password_hash and
password_verify

Related

How to prevent duplicate data in sql databse

I have a form where i save students login data to a database. The form includes the "admission_number", "username" and "password" fields. i want to show an error if the admission number is already existing and a user tries to add it again. Here's my php code for inserting the record.
<?php
if(isset($_POST['submit']))
{
$server = 'localhost';
$username = 'root';
$password = '';
$course_code=$_POST['course_code'];
$course_title=$_POST['course_title'];
$course_units=$_POST['course_units'];
$course_semester=$_POST['course_semester'];
$con=($GLOBALS["___mysqli_ston"] = mysqli_connect($server, $username, $password));
if(!$con)
{
exit('Error: could not establish connection to the server');
}
else
{
$con_db=((bool)mysqli_query($con, "USE esther"));
if(!$con_db)
{
exit('Error: Failed to connect to the database');
}
else
{
if(!empty($course_code) && !empty($course_title) && !empty($course_units) && !empty($course_semester))
{
$insert="INSERT INTO `course_table` VALUES('', '".$course_code."' ,'".$course_title."','".$course_units."','".$course_semester."')";
$query=mysqli_query($GLOBALS["___mysqli_ston"], $insert);
$dup_admission_number = mysql_query("SELECT admission_number FROM users_table WHERE admission_number = $admission_number");
}
if (#mysql_query($dup_admission_number)) {
echo 'Your admission number is already in our database.';
exit;
}
if($query)
{
echo 'course added successfully!';
header("location:add_course.php");
}
else { echo 'Error while adding Course.'; }
}
else
{
echo '*** fields cannot be blank ***.';
}
}
}
?>
To check admission number is unique or not you have to execute bellow query
$sql: "select id from student where admission_number = <> LIMIT 0,1";
if this query show result then you current form's admission number is not unique.
this process you can do using ajax request or you can check it before insert query being process.
or you can manage it in mysql by giving unique key constraint to admission number.
This is the Mysql Query
INSERT INTO sometable (data1, data2, data13)
SELECT 'username' FROM sometable
WHERE NOT EXISTS
(SELECT username FROM sometable WHERE login='someusername');

displaying server error messages on UI in php

I am very new to php programming. I have written a sign up html file where the user enters his email and password. If the user has already registered, I am redirecting to sign-in screen and if the user is new use, I am persisting in the database. Now if the user enters wrong password, he will again be redirected to sign-in screen but this time I want to show a message on the screen, that the password entered is incorrect. The sign in screen should not display the message when the user navigates directly to the sign in screen.
The code snippet is shown below:
<?php
define('DB_HOST', 'hostname');
define('DB_NAME', 'db_name');
define('DB_USER','username');
define('DB_PASSWORD','password');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser() {
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO WebsiteUsers (email,pass) VALUES ('$email','$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data) {
header('Location: reg-success.html');
}
}
function SignUp() {
if(!empty($_POST['email'])){
$emailQuery = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]'");
if($row = mysql_fetch_array($emailQuery)) {
$query = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]' AND pass = '$_POST[password]'");
if($row = mysql_fetch_array($query)) {
echo 'validated user. screen that is accessible to a registered user';
}else{
echo 'Redirect to the sign in screen with error message';
}
}else{
NewUser();
}
}
}
if(isset($_POST['submit']))
{
SignUp();
}
?>
Please let me know how to get this implementation using php
Here are a couple of classes that may help you prevent injection hacks plus get you going on how to do what you are trying to do in general. If you create classes for your tasks, it will be easier to re-use what your code elsewhere. I personally like the PDO method to connect and grab info from a DB (you will want to look up "binding" to help further prevent injection attacks), but this will help get the basics down. This is all very rough and you would want to expand out to create some error reporting and more usable features.
<?php
error_reporting(E_ALL);
// Create a simple DB engine
class DBEngine
{
protected $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
$rows = $query->fetchAll();
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
// Your user controller class
class UserControl
{
public $_error;
protected $db;
// Save the database connection object for use in this class
public function __construct($db)
{
$this->_error = array();
$this->db = $db;
}
// Add user to DB
protected function Add()
{
$email = htmlentities($_POST['email'],ENT_QUOTES);
// Provided you have a php version that supports better encryption methods, use that
// but you should do at least a very basic password encryption.
$password = hash('sha512',$_POST['password']);
// Use our handy DBEngine writer method to write your sql
$this->db->Write("INSERT INTO WebsiteUsers (`email`,`pass`) VALUES ('$email','$password')");
}
// Fetch user from DB
protected function Fetch($_email = '')
{
$_email = htmlentities($_email,ENT_QUOTES);
$password = hash('sha512',$_POST['password']);
// Use our handy DBEngine fetcher method to check your db
$_user = $this->db->Fetch("SELECT * FROM WebsiteUsers WHERE email = '$_email' and password = '$password'");
// Return true if not 0
return ($_user !== 0)? 1:0;
}
// Simple fetch user or set user method
public function execute()
{
// Check that email is a valid format
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// Save the true/false to error reporting
$this->_error['user']['in_db'] = $this->Fetch($_POST['email']);
// Asign short variable
$_check = $this->_error['user']['in_db'];
if($_check !== 1) {
// Add user if not in system
$this->Add();
// You'll want to expand your add feature to include error reporting
// This is just returning that it made it to this point
$this->_error['user']['add_db'] = 1;
}
else {
// Run some sort of login script
}
// Good email address
$this->_error['email']['validate'] = 1;
}
else
// Bad email address
$this->_error['email']['validate'] = 0;
}
}
// $_POST['submit'] = true;
// $_POST['email'] = 'jenkybad<script>email';
// $_POST['password'] = 'mypassword';
if(isset($_POST['submit'])) {
// Set up a db connection
$db = new DBEngine('hostname','dbname','dbuser','dbpass');
// Create instance of your user control
$_user = new UserControl($db);
// Execute instance
$_user->execute();
// Check for basic erroring
print_r($_user->_error);
} ?>

Admin Page Access

I have a page which only admins can access once they click a link. If the logged in user is a standard user then they should not be able to access the page. However, when a standard user tries to access the admin page they have access to the page.
I would appreciate a pair of second eyes to see if they can spot anything wrong with the code which would make the functionality work as intended.
Thanks
<?php
if(check_login() && isAdmin()) {
echo 'welcome administrator';
} else {
header('Location: login.php');
exit;
}
function isAdmin() {
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT * FROM `usertable` WHERE userID ='" . $_SESSION['sess_uid'] . "'";
$mainaccess = $conn->query($sql);
print_r($mainaccess);
if(!$mainaccess){
echo $conn->error;
}
if ($mainaccess -> userLevel == 0) {
return true;
} else {
return false;
}
}
function check_login () {
if(isset($_SESSION['sess_uid']) && $_SESSION['sess_uid'] != '') {
return true;
} else {
false;
return;
}
}
?>
The issue is that you are selecting from the database users where they have admin access already ie
SELECT `userID` FROM `usertable` WHERE `userLevel` = 0
So you are always showing anyone as an admin. The query needs to be changed to check specifically if the logged in user is an admin. So changing the query to something like so
$sql = "SELECT * FROM `usertable` WHERE userID = $_SESSION['sess_uid']";
Where $_SESSION['sess_uid'] is the userID
We have to remove both the userLevel check, as this is irrelevant when selecting the user, we also have to change from SELECT userID, to SELECT *, as if you only select the userID, you will not have the userLevel in your array and the line
$mainaccess -> 'userLevel' == 0
Will not work. By selecting everything you ensure all attributes can be accessed, ie
$mainaccess -> 'userLevel'
$mainaccess -> 'userID'
Update
The correct way to access the table data will be using either
Object (this is the method you will use)
$mainaccess -> 'userLevel'// Incorrect
$mainaccess->userLevel //correct
Array
$mainaccess -> 'userLevel'// Incorrect
$mainaccess['userLevel'] //correct
Please change this line
You query is also incorrect please use this block of code as your sql query is not pulling in the right info.
function isAdmin()
{
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT * FROM `usertable` WHERE userID = $_SESSION['sess_uid']";
if($result = $mainaccess = $conn->query($sql))
{
while($obj = $result->fetch_object())
{
$user = $obj;
}
}
if ($user->userLevel == 0)
{
return true;
}
else
{
return false;
}
}
You really need something like:
function isAdmin() {
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT `userID` FROM `usertable` WHERE `userLevel` = 0 AND userID ='" . $_SESSION['sess_uid'] . "'";
As I said in the comments, you are looking for ANYONE with admin access, but you really want to know whether THIS user has admin access, therefore you have to validate what user you are trying to figure out has access. I just put the code together above, thinking you are storing the userID in the session (as per your later code) but you may need to change this
Your approach is wrong. The link should only be shown to logged in admins.
Try something like this test code.
<?php
session_start();
$_SESSION['admin'] = 0;//set only by logging in
$html ="Test<br>";//page html
if ($_SESSION['admin']== 0) {
$html .="<a href=\"adminpage.php\" >Admin</a>";
}
echo $html;
?>
Modify to suit your requirements.

Query and Fetch Comparison SQLite

I'm just creating a simple login script to check the username/password, if there's a match with the database then it'll login. I think I have most of it, it opens up the database, grabs username/pw from the login. I think I set up my query right also that it grabs the username and pw. How would I go about comparing it? I've been stuck on this for quite a while. My fetch isn't working correctly also, it gives me an error. I'm very new to SQLite/Databases so this may seem very bad code but I'm trying my best.
<?php
//opens database
class MyDB extends SQLite3
{
function __construct()
{
$this->open('UserAccounts.db');
}
}
$db = new MyDB();
//username and pw from index.html
$user = $_REQUEST['myusername'] ;
$pw = $_REQUEST['mypassword'] ;
//if there is a database, it opens.
if(!$db){
echo $db->lastErrorMsg();
} else {
//Test to see if things are working correctly.
echo "Opened database successfully\n";
echo "$user";
echo "$pw";
}
$result = $db->query("SELECT * FROM login WHERE user = '$user' AND password = '$pw'");
if ($result->fetchColumn() == $user) {
$_SESSION['loggedin'] = true;
echo "Success";
};
if(!$_SESSION['loggedin']){
echo "Didn't Work";
exit;
};
Probably looks like this:
$fromDB = $result->fetchArray();
if ($fromDB['user'] == $user) {

check if username exists and generate new username if it does PHP

I am trying to write a simple function that checks if a username exists in the db and if so to call another function to generate a new username. My code seems to fall over though:
Username Function:-
$user1=create_username($fname, $company);
function create_username($surname, $company){
//$name_method=str_replace(" ", "", $surname);
$name_method=$surname.$forename;
$company_name_method=str_replace(" ", "", $company);
if(strlen($name_method)<=5)
{
$addition=rand(11,99);
$first=$addition.$name_method;
}
else
{
$first=substr($name_method,0,5);
}
if(strlen($company_name_method)<=5)
{
$addition2=rand(11,99);
$second=$addition2.$company_name_method;
}
else
{
$second=substr($company_name_method,0,5);
}
$middle=rand(100,1000);
$username=$first.$middle.$second;
return($username);
}
Check Username Function:
check_user($user1, $dbc, $fname, $company);
function check_user($user1, $dbc, $surname, $company){
$check_username="SELECT username FROM is_user_db WHERE username='$user1'";
$resultx=mysqli_query($dbc, $check_username) or die("Could not check username");
$num_rows=mysqli_num_rows($resultx);
if($num_rows>0)
{
$user1=create_username($fname, $company);
check_user($user1, $dbc, $fname, $company);
}
else
{
return($user1);
}
}
It just seems to return the original username.
You probably need to re-factor your code a little. Write out the steps on paper; that helps me. So far, I can see:
You want to check a username is unique on form submission
If it's not, generate a new username
So, check the username when your form is POSTed:
<?php
if (isset($_POST['submit'])) {
if (username_unique($_POST['username'])) {
// carry on processing form
}
else {
$suggested_username = suggest_username($_POST['username']);
// display form, with new suggested username?
}
}
And then write your functions:
<?php
// following on from code from above
function check_username($username) {
// get database connection (I use PDO)
$sql = "SELECT COUNT(*) AS count FROM users_tbl WHERE username = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($username));
$row = $stmt->fetchObject();
return ($row->count > 0); // if 'count' is more than 0, username already exists
}
function suggest_username($username) {
// take username, and add some random letters and numbers on the end
return $username . uniqid();
}
Hopefully this will help. Obviously it'll need some modification to work in your set-up, but this is the general flow you'll need.

Categories